[英]WPF with WindowsFormsHost Drag and Drop
当我从桌面拖动文件时,我正在努力在WindowsFormsHost
上进行拖放工作,但Drop
事件不会触发。
我创建了一个示例项目来演示:
您需要参考WindowsFormsIntegration
和System.Windows.Forms
MainWindow.xaml
<Window x:Class="WpfApp3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
mc:Ignorable="d"
AllowDrop="true"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel>
<WindowsFormsHost
Background="red"
Height="200"
AllowDrop="true"
Drop="WindowsFormsHost_Drop">
<wf:MaskedTextBox Height="200" x:Name="mtbDate" Mask="00/00/0000"/>
</WindowsFormsHost>
<ListBox Name="LogList" />
</StackPanel>
</Grid>
</Window>
MainWindow.xaml.cs
using System.Windows;
namespace WpfApp3
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
LogList.Items.Add("initialized");
}
private void WindowsFormsHost_Drop(object sender, DragEventArgs e)
{
LogList.Items.Add("fileDropped");
LogList.Items.Add($"FileSource: {e.Source}");
}
}
}
谁能告诉我我错过了什么?
好吧,我对此进行了一些测试,我只能猜测这是由于 WinForms 和 WPF 不兼容。 根据我的研究,当涉及这些技术时,事件并不总是通过控件进行。
但我可以建议一些解决此限制的方法 - 将事件保留在 WPF 控件中,因此定义不可见的底层控件(它将占据与WindowsFormsHost
完全相同的区域)以捕获事件:
<Grid>
<Border
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
AllowDrop="True"
Background="Transparent"
Drop="WindowsFormsHost_Drop" />
<WindowsFormsHost
Name="wfh"
Height="200"
Background="red">
<wf:MaskedTextBox
x:Name="mtbDate"
Height="200"
Mask="00/00/0000" />
</WindowsFormsHost>
</Grid>
我认为您甚至可以尝试将WindowsFormsHost
的IsHitTestVisible
设置为false
,因此所有 UI 事件都应该通过 - 但您可以自行测试并决定是否需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.