我在 Window 11 上运行以下简单的 WinUI 3 桌面应用程序。将文件从资源管理器拖到窗口中不起作用。
Grid_DragOver()
未被呼叫。我只是得到红色光标符号,就好像不允许放置一样:
我做错了什么?我必须激活某种功能吗?
奇怪的是,如果我从资源管理器“开始”部分的“最近”项目中拖动文件,它就会起作用: 但所有其他地方(例如桌面)都不起作用。
MainWindow.xaml:
<Grid AllowDrop="True" Drop="Grid_Drop" DragOver="Grid_DragOver" Background="LightGray">
<TextBlock
x:Name="FileNameTextBlock"
Text="Drag a file here"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="20"
FontWeight="Bold" />
</Grid>
</Window>
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;
using System;
using System.IO;
using Windows.ApplicationModel.DataTransfer;
using Windows.Storage;
namespace FileDragDropApp
{
public sealed partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
}
private async void Grid_Drop(object sender, DragEventArgs e)
{
// Check if the dropped data contains files
if (e.DataView.Contains(StandardDataFormats.StorageItems))
{
// Get the file(s) from the DataPackage
var items = await e.DataView.GetStorageItemsAsync();
if (items.Count > 0)
{
// Display the first file's name
var storageFile = items[0] as StorageFile;
if (storageFile != null)
{
FileNameTextBlock.Text = $"File: {storageFile.Name}";
}
}
}
}
private void Grid_DragOver(object sender, DragEventArgs e)
{
// This is not being called
e.AcceptedOperation = DataPackageOperation.Copy;
}
}
}
我也测试过DragEnter
。同样的结果。
<StackPanel AllowDrop="True" DragEnter="Grid_DragEnter" Background="LightGray">
<TextBlock
Text="Drag a file here"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="20"/>
</StackPanel>
private void Grid_DragEnter(object sender, DragEventArgs e)
{
Debug.WriteLine("Grid_DragEnter");
}
Grid_DragEnter
未被呼叫。干净重启。没什么。
测试于:Windows 11 专业版
24H2版本
操作系统版本 26100.2161
体验 Windows 功能体验包 1000.26100.32.0
Microsoft.Windows.SDK.BuildTools 10.0.26100.1742
Microsoft.WindowsAppSDK 1.6.240923002