[英]return value after window closes WPF-MVVM
我有一个仅包含一个文本框和保存按钮的用户控件。 我将此用户控件显示为“对话框”窗口。 用户在文本框中输入评论并单击“保存”按钮后,我将关闭对话框窗口。
我成功做到了。 我的问题是我想将文本框值传递到主窗口。 我该如何通过? 这是我的代码
//显示窗口
var window = new RadWindow
{
Owner = Application.Current.MainWindow,
WindowStartupLocation = WindowStartupLocation.CenterOwner
};
window.Content = control;
window.SizeToContent = true;
window.Header = header;
window.ShowDialog()
使用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
}
只需通过控件上的属性公开值:
public string TheValue
{
get { return theTextBox.Text; }
}
并从显示对话框的位置阅读它:
window.ShowDialog();
string value = control.TheValue;
(不确定为什么标记了问题“ MVVM”,因为您发布的代码似乎不遵循MVVM模式)
您正在使用ShowDialog
,但没有使用它的任何出色功能...
在显示对话框的类中:
if (window.ShowDialog() && window.DialogResult.Value == true)
{
//Access the properties on the window that hold your data.
}
然后在对话框本身中:
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.