怎样才能从viewmodel命令关闭窗口?
您不需要将View实例传递给ViewModel图层。 您可以訪問主窗口這樣的 -
Application.Current.MainWindow.Close()
我看到了如上所述的ViewModel类访问你的主窗口没有问题。 按照MVVM原则,View和ViewModel之间不应该有紧密的耦合,即它们应该忽略其他操作。 在这里,我们没有将任何东西传递给View中的ViewModel。
我这样做是通过创建一个附加属性叫的DialogResult:
public static class DialogCloser
{
public static readonly DependencyProperty DialogResultProperty =
DependencyProperty.RegisterAttached(
"DialogResult",
typeof(bool?),
typeof(DialogCloser),
new PropertyMetadata(DialogResultChanged));
private static void DialogResultChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var window = d as Window;
if (window != null && (bool?)e.NewValue == true)
window.Close();
}
public static void SetDialogResult(Window target, bool? value)
{
target.SetValue(DialogResultProperty, value);
}
}
然后写这个给你XAML,在窗口标签
<Window x:Class="FrmOpenProject"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
local:DialogCloser.DialogResult="{Binding Close}"
>
</Window >
终于在视图模型
private bool close;
public bool Close
{
get { return close; }
set
{
if (close == value)
return;
close = value;
RaisePropertyChanged(() => Close);
}
}
如果将Close更改为true,则窗口将被关闭
Close = True;
这篇博客探讨了在MVVM模式中如何从ViewModel层关闭窗口,避免View和ViewModel之间的紧密耦合。作者建议使用附加属性DialogResult,并在XAML中设置,然后在ViewModel中更改该属性来关闭窗口。
4万+

被折叠的 条评论
为什么被折叠?



