单击 WindowsFormsHost 内的按钮时关闭 WPF 对话框

Close the WPF dialog when one clicks on a button inside the WindowsFormHost

我有一个 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时,我要

  1. 要关闭的 WPF 对话框
  2. 并且数据importantdata要"pass out"到调用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
    
        }
    }
    

例如,您可以将 属性 添加到公开 Button 控件的 WinForms 控件:

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 对话框 window:

的代码隐藏中连接到 ButtonClick 事件
public partial class Dialog : Window
{
    public Dialog()
    {
        InitializeComponent();
        winFormsControl.TheButton.Click += (s, e) => this.Close();
    }
}

一旦 ShowDialog 方法 returns:

打开对话框的 window 就可以访问 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