转 MVVM模式下关闭窗口的实现
程序员文章站
2022-07-13 22:38:03
...
转自https://www.cnblogs.com/XzcBlog/p/4876816.html
通过行为来实现
实现界面与逻辑的分离
窗口关闭行为:其中含有布尔型的Close属性,将相应的关闭行为绑定到该属性上,则可以实现窗口的关闭行为,从而实现VM与View的分离
public class WindowCloseBehaviour : Behavior<Window>
{
public static readonly DependencyProperty CloseProperty =
DependencyProperty.Register(
"Close",
typeof(bool),
typeof(WindowCloseBehaviour),
new FrameworkPropertyMetadata(
false,
OnCloseChanged));
public bool Close
{
get { return (bool)GetValue(CloseProperty); }
set { SetValue(CloseProperty, value); }
}
private static void OnCloseChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var window = ((WindowCloseBehaviour)d).AssociatedObject;
var newValue = ((bool)e.NewValue);
if (newValue)
{
window.Close();
}
}
View:
xmlns:event="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
而behaviors则是声明的WindowCloseBehaviour的命名空间
<event:Interaction.Behaviors>
<behaviors:WindowCloseBehaviour Close="{Binding IsWinClose}"/>
</event:Interaction.Behaviors>
ViewModel:
private bool _isWinClose;
/// <summary>
/// 指示窗口是否关闭
/// </summary>
public bool IsWinClose
{
get { return _isWinClose; }
set
{
_isWinClose = value;
OnPropertyChanged("IsWinClose");
//窗口关闭则重置窗口状态
if (IsWinClose)
{
ResetWindowCloseState();
}
}
}
//重置窗口状态
private void ResetWindowCloseState()
{
IsWinClose = false;
}
在业务逻辑中只需要指定isWinClose = true那么就能够关闭窗口了;
当然实现的方式有很多种,用附加属性也是能够实现的;这里使用行为的话是为了指定类型从而避免附加属性的类型判断