简体   繁体   中英

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
    }

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM