Tuesday, October 4, 2016

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

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<string> 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();
    }
}

Reference:

http://stackoverflow.com/questions/21607925/c-sharp-return-variable-from-child-window-to-parent-window-in-wpf

No comments: