C# - Return variable from child window to parent window in WPF

前端 未结 3 1651
滥情空心
滥情空心 2020-12-16 23:45

I have a main window called form1. in form1 I have a button, when it is pressed it will open form2 (form2.ShowDialog()). In form2 I have a button called \"Check\". When the

3条回答
  •  离开以前
    2020-12-17 00:34

    Create an event in your second window, have the parameters of the event's delegate contain whatever information you want to pass:

    public class Popup : Window
    {
        public event Action Check;
    
        public void Foo()
        {
            //fire the event
            if (Check != null)
                Check("hello world");
        }
    }
    

    Then the main window can subscribe to that event to do what it wants with the information:

    public class Main : Window
    {
        private Label label;
        public void Foo()
        {
            Popup popup = new Popup();
            popup.Check += value => label.Content = value;
            popup.ShowDialog();
        }
    }
    

提交回复
热议问题