gpt4 book ai didi

.net - 实现 WPF MVVM 模式以关闭表单时获取 "DialogResult can be set only after Window is created and shown as dialog"

转载 作者:行者123 更新时间:2023-12-03 11:06:14 28 4
gpt4 key购买 nike

我正在尝试实现 this WPF 表单关闭的 MVVM 模式也在此 blog 中进行了解释并且我收到 System.InvalidOperationException 和错误消息“DialogResult can be set only after Window is created and show as dialog.”当我尝试在关闭按钮命令上设置对话框结果时:

DialogResult = true;

这是我的 View 模型:
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 View :
<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() 打开的表单上设置对话框结果时,您会收到此错误。

关于.net - 实现 WPF MVVM 模式以关闭表单时获取 "DialogResult can be set only after Window is created and shown as dialog",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8326153/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com