WPF MVVM模式下关闭窗体
需求一:在View层关闭窗体:
一、首先给窗体起个名字,name=“window”;
name="window"
二、给按钮控件绑定命令,并把窗体名字作为参数;
<Button Command={Binding CloseWindowCommand} CommandParameter={Binding ElementName=window}/>
三、在ViewModel层按钮的绑定命令函数中处理关闭功能:(obj为View层传递的参数,即窗体名称)
this.CloseWindowCommand.DoExecute = new Action<object>((o) =>
{
(o as Window).Close();
});
需求二:在ViewModel层通过属性关闭窗体:
关闭窗口的方法:借助System.Windows.Interacivity里面的Behavior,把“LoginViewModel.cs”里面的属性,关联到LoginView.xaml层的一个事件(Window.Close())
一、在“Common”文件夹,新建“WindowManagerBehavior.cs”类,定义关闭行为
public class WindowBehavior : Behavior<Window>
{
/// <summary>
/// 关闭窗口
/// </summary>
public bool Close
{
get { return (bool)GetValue(CloseProperty); }
set { SetValue(CloseProperty, value); }
}
public static readonly DependencyProperty CloseProperty =
DependencyProperty.Register("Close", typeof(bool), typeof(WindowBehavior), new PropertyMetadata(false, OnCloseChanged));
private static void OnCloseChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var window = ((WindowBehavior)d).AssociatedObject;
var newValue = (bool)e.NewValue;
if (newValue)
{
window.Close();
}
}
}
二、在ViewModel.cs里面的定义ToClose属性:
private bool isClose;
public bool IsClose
{
get { return isClose; }
set
{
isClose = value; this.DoNotify();
//if (isClose)
//{
// this.DoNotify();
//}
}
}
三、引用System.Windows.Interactivity.dll。安装“管理NuGet程序包”下载,并在界面中引用。
xmlns:i ="http://schemas.microsoft.com/expression/2010/interactivity"
四、在前端View.xaml进行绑定
<i:Interaction.Behaviors>
<common:WindowBehavior Close="{Binding IsClose}"/>
</i:Interaction.Behaviors>
五、最后可以通过绑定命令或者在其他函数中给IsClose属性赋值true即可关闭窗体。
IsClose = true;//关闭窗体