当我从桌面上拖放一个文件时,Drop事件就是不能触发,我很难在WindowsFormsHost上完成拖放工作。
我创建了一个示例项目来演示:
您需要引用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}");
}
}
}谁能告诉我我错过了什么?
发布于 2021-02-12 19:26:04
好吧,我测试了一下,我只能猜测这是由于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事件都应该失败--但这取决于您测试和决定是否需要它。
https://stackoverflow.com/questions/66170199
复制相似问题