实现"保存和关闭"操作的 MVVM 方法是什么?



我在应用程序中有一个设置窗口,其中有一个按钮用于"保存和关闭";行动。

现在,视图模型知道如何保存数据,命令驻留在那里,并通过Xaml中的{Binding ...}链接。

要关闭窗口,我将元素本身作为命令参数传递。我不关心它在实践中,但我想知道一个"很好的MVVM方法"。解决这个问题的方法。在这种情况下,保持UI行为分离的理想/教科书方式是什么?

关闭窗口是视图的职责,因此应该由视图中的某些东西来完成。通过视图模型保存数据是模型的职责。你需要的是视图中会关闭那个窗口的东西。以及告诉它从视图模型关闭的方式。视图模型告诉视图发生变化的最明显的方法是绑定。

我的方法是绑定来自视图模型的命令。该命令执行保存操作,然后设置绑定bool属性。视图绑定到这个属性并关闭自己。这样,视图模型就不需要任何对窗口的引用。它所做的只是设置它的一个属性。

这里有一些代码给你一个感觉。
我想只要你看到它,你就会明白了。有一个类继承自没有ui的控件。CloseMe看起来像:

public class CloseMe : Control
{
public bool? Yes
{
get
{
return (bool?)GetValue(YesProperty);
}
set
{
SetValue(YesProperty, value);
}
}
public static readonly DependencyProperty YesProperty =
DependencyProperty.Register("Yes",
typeof(bool?),
typeof(CloseMe),
new PropertyMetadata(null, new PropertyChangedCallback(YesChanged)));
private static void YesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if ((bool?)e.NewValue != true)
{
return;
}
var me = (CloseMe)d;
Window parent = Window.GetWindow(me) as Window;
parent.Close();
}
}

在我的窗口:

<local:CloseMe Yes="{Binding CloseWindow, Mode=TwoWay}"/>

CloseWindow是我在视图模型中提到的bool属性。将其设置为true, CloseMe控件YesProperty将更改为true。回调触发并在可视树中查找它的父窗口。然后它会关闭那个窗口,然后……做。

这可能是最好的MVVM方法之一:

  1. 通过Nuget安装更新的microsoft . xml . actions . wpf
Install-Package Microsoft.Xaml.Behaviors.Wpf
  1. 在xml文件中(即视图),添加xmlns名称空间
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
  1. 在xml文件中(即视图),添加Closing Binding:
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closing">
<i:InvokeCommandAction  Command="{Binding CloseCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
  1. 最后,在ViewModels中定义命令

最新更新