简体   繁体   English

窗口关闭后返回值WPF-MVVM

[英]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 使用ICommand在ViewModel中关闭窗口

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) (不确定为什么标记了问题“ MVVM”,因为您发布的代码似乎不遵循MVVM模式)

You are using ShowDialog , but not any of the wonderful features it has... 您正在使用ShowDialog ,但没有使用它的任何出色功能...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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