[英]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.