当我的应用程序中出现错误时,我试图显示一个对话框窗口。当视图模型想要启动对话框时,它会触发一个事件,并且视图的代码通过创建一个新的对话框窗口并显示它来响应。我遇到的问题是我无法将任何信息传递给对话框(如错误消息),因为当我创建 DialogView 时 DialogViewModel 未加载。
我在 DialogView 构造函数上尝试了这个:
public DialogView() {
InitializeComponent();
var vm = (DialogViewModel)DataContext;
if( vm != null ) {
vm.ErrorInfo= "Sample error message";
}
}
但这不起作用,因为 DialogViewModel 为空。
DataContext
(或 Content
属性,具体取决于您处理对话框布局的方式)。MainWindow.xaml.cs
partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var mainViewModel = new MainViewModel();
// TODO::Create the ErrorChanged event and the ErrorChangedEventArgs (EventHandler<ErrorChangedEventArgs>)
mainViewModel.ErrorChanged += OnViewModelErrorChanged;
this.DataContext = mainViewModel;
}
private void OnViewModelErrorChanged(object sender, ErrorChangedEventArgs e)
{
// Consider to pass the error info to the constructor
var errorDialogViewModel = new DialogViewModel() { ErrorInfo = e.Message };
var errorDialog = new DialogView() { DataContext = errorDialogViewModel };
erorDialog.ShowDialog();
}
}