c# - ShowDialog 在 WPF 中的处理方式是否与 Winforms 不同?

标签 c# wpf winforms visual-studio-2012 event-handling

我在将我的 Winforms 程序转换为 WPF 程序时遇到了另一个问题。在我的第一个程序中,我打开了一个较小的窗口以允许用户调整一些数据,然后当它关闭时,另一个窗体会再次激活并显示新数据。

我使用 form2.ShowDialog(); 打开窗体,这会自动使父窗体在 Winforms 中停用。这样,当我关闭 form2 时,父表单被激活,并且我能够使用事件处理程序 form1_Activated 成功地重新加载和重新初始化一些设置。

但是,现在当我尝试用 WPF 做同样的事情时,我仍然可以使用 form2.ShowDialog(); 打开 form2,但是当我关闭表单时,它不会注册 form1_Activated 事件处理程序。相反,为了重新加载设置,我必须单击另一个窗口,然后返回我的程序以注册 form1_Activated 事件处理程序。

我只是做错了什么,还是我应该在 WPF 中使用另一个事件处理程序来实现我在 Winforms 中能够做的同样的事情?

最佳答案

调用 ShowDialog() 会导致对话框顶部以模态模式出现,所以我不明白为什么您需要一个事件处理程序来在对话框关闭后处理结果。请记住,您也可以访问 DialogBox 中的公共(public)变量。如果我理解你的问题,这应该可以满足你的要求:

主窗口:

My_DialogBox dlg = new My_DialogBox();
dlg.Owner = this;
dlg.MyPublicVariable = ''; //some value that you might need to pass to the dialog
dlg.ShowDialog();  //exection of MainWindow is suspended until dialog box is closed

if (dlg.DialogResult == true)
{
    //dlg.MyPublicVariable is still accessible 
    //call whatever routines you need in order to refresh the main form's data
}

对话框:

private void OK_Button_Click(object sender, RoutedEventArgs e)
{
    MyPublic variable = something;  //accessible after the dialog has closed.
    this.DialogResult = true;
}

private void Cancel_Button_Click(object sender, RoutedEventArgs e)
{
     this.DialogResult = false;
}

有关对话框的 MSDN 文章非常好。可能有一些提示可能对您有更多帮助: http://msdn.microsoft.com/en-us/library/aa969773.aspx

祝你好运!

关于c# - ShowDialog 在 WPF 中的处理方式是否与 Winforms 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17457400/

相关文章:

C# : Console. Read() 未获取 "right"输入

wpf - 在 WPF 中存储事件处理程序方法的位置 - MVVM

vb.net - Windows Media Player 持续时间 - WinForms

c# - 显示 2 位小数(除非有更多有效数字)

c# - 尝试使用 C# 连接 Couchbase 服务器时返回内部异常

wpf - WPF 是 WinForms 的替代品吗?

c# - 线程无法访问对象

c# - .NET 设置图片显示大小

c# - 如何在图像按钮中将背景图像设置为无或其他默认值?

c# - 通过单击指向子页面的母版页超链接获取值