如何从ViewModel关闭Window
public static class DialogCloser { public static readonly DependencyProperty DialogResultProperty = DependencyProperty.RegisterAttached( "DialogResult", typeof(bool?), typeof(DialogCloser), new PropertyMetadata(DialogResultChanged)); private static void DialogResultChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var window = d as Window; if (window != null) { window.DialogResult = e.NewValue as bool?; } } public static void SetDialogResult(Window target, bool? value) { target.SetValue(DialogResultProperty, value); } }
注册一个DialogResult依赖属性
然后在View端绑定这个依赖属性DialogResult:
<Window x:Class="mvvm_demo_close_window.ChildWindow" ... xmlns:xc="clr-namespace:mvvm_demo_close_window" xc:DialogCloser.DialogResult="{Binding DialogResult}">
然后在ViewModel端将这个当做正常的依赖属性去操作就行了,当this.DialogResult=true的时候就自动在ViewModel关闭了子窗口:
public class ChildWindowViewModel : ViewModelBase { private bool? dialogResult; public bool? DialogResult { get { return this.dialogResult; } set { this.dialogResult = value; RaisePropertyChanged("DialogResult"); } } //用来接收关闭按钮的Command public ICommand CloseCmd { get { return new DelegateCommand((obj) => { this.DialogResult = true; }); } } }
原文地址:https://www.cnblogs.com/SilveryBullet/p/8384919.html