我有一个WPF对话框,它承载一个windowsFormHost控件,如下所示
<Window x:Class="WPFSort.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:local="clr-namespace:WPFSort"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<WindowsFormsHost HorizontalAlignment="Left" Height="Auto"
Margin="87,43,0,0" VerticalAlignment="Top" Width="Auto">
<local:SimpleWinControl />
</WindowsFormsHost>
</Grid>
</Window>
对于 SimpleWinControl,它是一个 WinForm 控件。单击button 1
时,我想要
- 要关闭的 WPF 对话框
数据
importantdata
"传递"到调用 WPF 对话框的 WPF 窗体?public partial class SimpleWinControl : UserControl { public SimpleWinControl() { InitializeComponent(); } public object importantdata; private void button1_Click(object sender, EventArgs e) { //how should I write the close and pass the importantdata out } }
例如,可以向 WinForms 控件添加一个公开Button
控件的属性:
public partial class SimpleWinControl : UserControl
{
public SimpleWinControl()
{
InitializeComponent();
}
public Button TheButton { get { return button1; } }
...
}
在 XAML 标记中为 WinForms 控件提供x:Name
:
<WindowsFormsHost HorizontalAlignment="Left" Height="Auto" Margin="87,43,0,0" VerticalAlignment="Top" Width="Auto">
<local:SimpleWinControl x:Name="winFormsControl" />
</WindowsFormsHost>
。并挂接到 WPF 对话框窗口的代码隐藏中Button
的Click
事件:
public partial class Dialog : Window
{
public Dialog()
{
InitializeComponent();
winFormsControl.TheButton.Click += (s, e) => this.Close();
}
}
一旦ShowDialog
方法返回,打开对话框的窗口就可以访问importantdata
字段:
private void ShowDialog_Click(object sender, RoutedEventArgs e)
{
Dialog d = new Dialog();
d.ShowDialog();
object importantData = d.winFormsControl.importantdata;
}
另一种选择可能是从 WinForms 控件引发事件:https://msdn.microsoft.com/en-us/library/5z57dxz2(v=vs.90).aspx