UWP拖拽操作中DragEnter与DragOver事件未触发问题求助
UWP拖拽文件显示禁止符号,DragEnter/DragOver事件未触发问题
我正在开发Windows平台的UWP桌面应用,实现拖拽功能时遇到异常:拖拽文件时始终显示禁止符号🚫,DragEnter和DragOver事件似乎未触发。未以管理员身份运行Visual Studio 2022,求解决。
相关代码
MainPage.xaml.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace XML2PDFConverter { /// <summary> /// Starting from a blank page. /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } private void BackgroundGrid_DragEnter(object sender, DragEventArgs e) { e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Move; } private async void BackgroundGrid_Drop(object sender, DragEventArgs e) { if (e.DataView.Contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.StorageItems)) { var items = await e.DataView.GetStorageItemsAsync(); var filePaths = items.Select(x => x.Path).ToList(); } } private void BackgroundGrid_DragOver(object sender, DragEventArgs e) { e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Move; } } }
MainPage.xaml
<Page x:Class="XMLToPDFConverter.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="XMLToPDFConverter" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Grid x:Name="BackgroundGrid" AllowDrop="True" DragEnter="BackgroundGrid_DragEnter" Drop="BackgroundGrid_Drop" DragOver="BackgroundGrid_DragOver" /> </Page>
解决方法
- 修正命名空间不一致问题:后台代码命名空间是
XML2PDFConverter,但XAML的x:Class是XMLToPDFConverter(注意2和To的差异),这会导致XAML与后台代码无法绑定,事件无法触发。需保持两者命名空间完全一致。 - 设置Grid有效尺寸:当前Grid未指定宽高,可能实际尺寸为0导致无法捕获拖拽事件。给Grid添加尺寸属性,确保它占据页面空间:
<Grid x:Name="BackgroundGrid" AllowDrop="True" DragEnter="BackgroundGrid_DragEnter" Drop="BackgroundGrid_Drop" DragOver="BackgroundGrid_DragOver" Width="Auto" Height="Auto" /> - 调整拖拽操作类型:如果是复制文件,建议将
AcceptedOperation设为Copy而非Move,避免系统权限限制;同时可在DragOver事件中隐藏默认禁止符号:private void BackgroundGrid_DragOver(object sender, DragEventArgs e) { e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Copy; e.DragUIOverride.IsGlyphVisible = false; } - 添加文件访问权限:若拖拽文件位于Documents、Downloads等受保护目录,需在
Package.appxmanifest中添加对应权限(如Documents Library或Downloads Library)。
内容的提问来源于stack exchange,提问作者Wt.N
相关产品推荐
相关产品推荐

