关闭窗口的方法:借助System.Windows.Interacivity
里面的Behavior
,把“LoginViewModel.cs”里面的属性,关联到LoginView.xaml层的一个事件(Window.Close())
1、在“Common”文件夹,新建“WindowManagerBehavior.cs”类,定义关闭行为
WindowManagerBehavior.cs代码如下:
using System.Windows;
using System.Windows.Interactivity;
namespace StudentMgrDemo.Common
{
public class WindowManagerBehavior:Behavior<Window>
{
//定义依赖属性
public static readonly DependencyProperty closeDP = DependencyProperty.Register("Close", typeof(bool), typeof(WindowManagerBehavior), new PropertyMetadata(false, OnCloseChanged));
private static void OnCloseChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var window = ((WindowManagerBehavior)d).AssociatedObject;
var newValue = (bool)e.NewValue;
if (newValue)
{
window.Close();
}
}
// <summary>
/// 关闭窗口
/// </summary>
public bool Close
{
get { return (bool)GetValue(closeDP); }
set { SetValue(closeDP, value); }
}
}
}
2、在LoginViewModel.cs里面的定义ToClose属性:
//是否关闭窗口
private bool toClose = false;
public bool ToClose
{
get { return toClose; }
set
{
toClose = value;
if (toClose)
{
this.RaisePropertyChanged("ToClose");
}
}
}
在Common文件夹,新建“NotiticationObject.cs”的RaisePropertyChanged方法:
using System.ComponentModel;
namespace StudentMgrDemo.Common
{
//INotifyPropertyChanged:实现接口
public class NotiticationObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
//定义一个“RaisePropertyChanged”方法,让它发起请求,需要一个string参数,让它监听属性
/// <summary>
/// 发起请求
/// </summary>
/// <param name="propertyName">属性名称:监听属性</param>
public void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
3、引用System.Windows.Interactivity.dll。安装“管理NuGet程序包”下载。
下载成功:
4、在前端LoginView.xaml进行绑定
5、LoginViewModel.cs
执行结果: