Return an object from a popup window
I have a Window which pop-ups another Window. I want the second Window to be able to return an object to the first Window when a button is pressed. How would I do this?
Solution 1:
You can expose a property on the second window, so that the first window can retrieve it.
public class Window1 : Window
{
...
private void btnPromptFoo_Click(object sender, RoutedEventArgs e)
{
var w = new Window2();
if (w.ShowDialog() == true)
{
string foo = w.Foo;
...
}
}
}
public class Window2 : Window
{
...
public string Foo
{
get { return txtFoo.Text; }
}
}
Solution 2:
If you don't want to expose a property, and you want to make the usage a little more explicit, you can overload ShowDialog
:
public DialogResult ShowDialog(out MyObject result)
{
DialogResult dr = ShowDialog();
result = (dr == DialogResult.Cancel)
? null
: MyObjectInstance;
return dr;
}