Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return an object from a popup window

Tags:

c#

wpf

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?

like image 749
Reflux Avatar asked Aug 12 '10 13:08

Reflux


3 Answers

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

}
like image 119
Thomas Levesque Avatar answered Nov 04 '22 11:11

Thomas Levesque


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;
}
like image 22
Robert Rossney Avatar answered Nov 04 '22 10:11

Robert Rossney


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" ... />
like image 6
Colin Avatar answered Nov 04 '22 09:11

Colin