仅在创建窗口并将其显示为对话框之后,才能设置"DialogResult".在实现WPF MVVM模式以关闭表单时 [英] Getting "DialogResult can be set only after Window is created and shown as dialog" when implementing WPF MVVM pattern for form closing
问题描述
我正在尝试为WPF表单关闭实现此 MVVM模式,该博客,我得到了System.InvalidOperationException错误消息仅在创建Window并显示为对话框之后才能设置DialogResult".当我尝试在关闭"按钮命令上设置对话框结果"时:
I am trying to implement this MVVM pattern for the WPF form closing which is also explained in this blog and I am getting System.InvalidOperationException with error message "DialogResult can be set only after Window is created and shown as dialog." when I am trying to set the Dialog Result on Close button command:
DialogResult = true;
这是我的ViewModel:
Here is my ViewModel:
class MainWindowViewModel:INotifyPropertyChanged
{
private bool? dialogResult;
public bool? DialogResult
{
get { return dialogResult; }
set
{
if (value != this.dialogResult)
{
this.dialogResult = value;
OnPropertyChanged("DialogResult");
}
}
}
public string Text
{
get { return "Hello!"; }
}
void CloseCommandExecute()
{
this.DialogResult = true;
}
这是XAML视图:
<Window x:Class="WpfApplication.Mvvm.Windowclosing.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication.Mvvm.Windowclosing"
local:DialogCloser.DialogResult="{Binding DialogResult}"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100"/>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<TextBlock Text="{Binding Text}" Grid.Row="0"/>
<Button Grid.Row="1" Command="{Binding CloseCommand}">Close Me</Button>
</Grid>
</Window>
我在做什么错了?
推荐答案
仅当使用ShowDialog()打开表单时,设置对话框结果才有效.当您尝试在使用Show()打开的表单上设置对话框结果时,会出现此错误.
Setting a dialog result only works when you open your form with ShowDialog(). You get this error when you try to set the dialog result on a form opened with Show().
这篇关于仅在创建窗口并将其显示为对话框之后,才能设置"DialogResult".在实现WPF MVVM模式以关闭表单时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!