标签:
通过行为来实现
实现界面与逻辑的分离
窗口关闭行为:其中含有布尔型的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"); } }
在业务逻辑中只需要指定isWinClose = true那么就能够关闭窗口了;
当然实现的方式有很多种,用附加属性也是能够实现的;这里使用行为的话是为了指定类型从而避免附加属性的类型判断
标签:
原文地址:http://www.cnblogs.com/XzcBlog/p/4876816.html