Chatra
Chatra

Reputation: 3139

return value after window closes WPF-MVVM

I am having a User Control which contains only one textbox and save button. I am showing this user control as Dialog window. After user enter comments in textbox and click on save button, I am closing the dialog window.

I am succesful doing this. My issue is I want to pass the textbox value to the main window. How can I pass this ? Here is my Code

//Showing the Window

 var window = new RadWindow
           {
              Owner = Application.Current.MainWindow,
              WindowStartupLocation = WindowStartupLocation.CenterOwner
           };          
        window.Content = control;
        window.SizeToContent = true;
        window.Header = header;  
        window.ShowDialog()

Closing the Window in ViewModel using ICommand

private void SaveCommentExecute()
    {
        var window = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);
        if (window != null)
        {
            window.Close();
        }
        // get comments and pass back to main window
    }

Upvotes: 1

Views: 7285

Answers (2)

Thomas Levesque
Thomas Levesque

Reputation: 292735

Just expose the value through a property on your control:

public string TheValue
{
    get { return theTextBox.Text; }
}

And read it from where you show the dialog:

window.ShowDialog();
string value = control.TheValue;

(not sure why you tagged your question "MVVM", because the code you posted doesn't seem to follow the MVVM pattern)

Upvotes: 2

Ron Beyer
Ron Beyer

Reputation: 11273

You are using ShowDialog, but not any of the wonderful features it has...

In the class that shows the dialog:

if (window.ShowDialog() && window.DialogResult.Value == true)
{
    //Access the properties on the window that hold your data.
}

And then in the dialog itself:

if (window != null)
{
    this.DialogResult = true;
    //Set the properties to the data you want to pass back.
    window.Close();
}

Upvotes: 1

Related Questions