Harry Boy
Harry Boy

Reputation: 4745

Pass a value back from a Window in WPF

I have a WPF application.

I am creating a new window like so whenever a button is pressed:

MyWindow myWin = new MyWindow();
myWin.Show();

And then in the constructor of MyWindow I'm setting its parent to the main Application like so:

  public MyWindow ()
  {
     InitializeComponent();

     this.Owner = App.Current.MainWindow;
   }

This enables the window to not appear as a separate window and stays in front of my application.

Now I want to pass a parameter back from MyWindow whenever it closes. How do I do this? Something like this:

string myValue = myWin.Value.

Can this be done in WPF?

Upvotes: 1

Views: 4240

Answers (3)

Garfield
Garfield

Reputation: 21

Do it like this

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

}

Upvotes: 2

poy
poy

Reputation: 10507

There doesn't need to be a WPF specific solution to this... Really you have a class that can have a public property that the original class can access.

Now, if you would like a "fancy" solution... You could have a TPL solution (assuming you are using .NET 4.5).

You could do something like

public class MyWindow
{
  private TaskCompletionSource<String> _tcs = new TaskCompletionSource<String>();

  public Task<String> Fetch()
  {
    return _tcs.Task;
  }

  public void handleButtonClick(object sender, EventArgs e)
  {
    _tcs.SetResult("some value");
  }
}

...

var window = new MyWindow();
window.Show();

var value = await window.Fetch()

Upvotes: 3

Chandan Kumar
Chandan Kumar

Reputation: 4638

change your code with this

MyWindow myWin = new MyWindow();
 myWin.ShowDialog();

Upvotes: 2

Related Questions