C# - Return variable from child window to parent window in WPF
Solution 1
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();
}
}
Solution 2
This answer while not perfectly on target will be more useful to people that google themselves here for the general solution of how to communicate between windows:
There is no reason at all to set up events to access objects of the Main Window of you application. You can simply call them on the popup code and be done with it:
((MainWindow)Application.Current.MainWindow).textBox1.Text = "Some text";
barack o mama
Updated on June 25, 2022Comments
-
barack o mama about 2 years
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 user clicks on "Check" it should do some validation and if successful creates a string object and return it to form1. Any Ideas on how to implement this? I don't want to return anything when the user closes the window.