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?
+4
A:
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; }
}
}
Thomas Levesque
2010-08-12 14:01:41
That doesn't work because the user interacts with the window and presses a button before I want the parent window to get the value.
Reflux
2010-08-12 14:39:45
I figured it out. The problem was it should be if(w.ShowDialog() == false).
Reflux
2010-08-12 14:50:11
@Reflux: are you sure ? ShowDialog returns false when the user cancels the dialog, so you probably don't want to take the value into account in that case
Thomas Levesque
2010-08-12 14:53:42
@ThomasProbably because the button the user presses in my case also closes the window.
Reflux
2010-08-12 15:30:36
You should set the DialogResult explicitly then
Thomas Levesque
2010-08-12 16:19:34
A:
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;
}
Robert Rossney
2010-08-12 19:21:37