Window2关闭时更新MainWindow?

时间:2015-05-09 02:36:08

标签: c# wpf xaml

我有一个双窗口应用程序。我从主窗口打开windows2。我想在window2关闭时更新mainWindow(例如更改文本)。我怎么能做到这一点。

这是我的主窗口

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Window2 secondForm;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            secondForm = new Window2();
            secondForm.Show();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

    private void Button_Click(object sender, RoutedEventArgs e) {
        SecondForm form = new SecondForm();
        form.Closed += form_Closed;
        form.Show();
    }

    void form_Closed(object sender, EventArgs e) {
        llMsg.Content = "The second form is closed";
    }

答案 1 :(得分:-1)

您可以通过传递MainWindow引用来完成此操作。

在Window2类

中添加一个名为MainWindow的属性,类型为Window
public Window MainWindow { get;set;}

然后更新了button1_click方法,如下所示。

    private void button1_Click(object sender, RoutedEventArgs e)
            {
                secondForm = new Window2();
                secondForm.MainWindow = this;
                 secondForm.OnClosing += (sfO,sfE)=>{ if(MainWindow!=null){
MainWindow.SomeProperty = "Second Window was closed.";
} };
                secondForm.Show();
            }

我使用Lambda表达式语法来捕获OnClosing事件。