Return an object from a popup window

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; }
    }

}

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;
}

Holy mother of Mars, this took me forever to figure out:

WINDOW 1:

if ((bool)window.ShowDialog() == true)
{
   Window2 content = window.Content as Window2;
   string result = content.result;
   int i = 0;
}

WINDOW 2:

public partial class Window2 : UserControl
{
    public string result
    {
        get { return resultTextBox.Text; }
    }

    public Window2()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Window.GetWindow(this).DialogResult = true;
        Window.GetWindow(this).Close();
    }
}

XAML:

<Button IsDefault="True" ... />

Tags:

C#

Wpf