关闭窗口是视图的责任,视图模型应该对此一无所知。难怪你会纠结在一起。如果在“按钮逻辑”运行时不需要窗口停留在屏幕上,那么只需使用
CompositeCommand
从Prism(我不太喜欢它,因为它使用代码隐藏,但没关系)或等效工具将两个命令绑定到按钮。另一方面,如果需要在“按钮逻辑”运行时保持窗口在屏幕上,例如显示进度,并且如果视图模型反映了这一点,则可以添加
bool IsButtonLogicComplete
属性到视图模型(不要忘记
INotifyPropertyChanged
)并通过以下附加属性/行为将窗口的“关闭”状态绑定到此属性:
public static class AttachedProperties
{
public static DependencyProperty ForceCloseProperty =
DependencyProperty.RegisterAttached ("ForceClose",
typeof (bool), typeof (AttachedProperties), new UIPropertyMetadata (false, (d, e) =>
{
var w = d as Window ;
if (w != null && (bool) e.NewValue)
{
w.DialogResult = true ;
w.Close () ;
}
})) ;
public static bool GetForceClose (DependencyObject obj)
{
return (bool) obj.GetValue (ForceCloseProperty) ;
}
public static void SetForceClose (DependencyObject obj, bool value)
{
obj.SetValue (ForceCloseProperty, value) ;
}
}
<!-- in .xaml -->
<Window
xmlns:local="clr-namespace:YourNamespace"
local:AttachedProperties.ForceClose="{Binding IsButtonLogicComplete}" ...
这将使您的视图和视图模型关注点保持良好的分离。