原文地址:https://blog.csdn.net/zang141588761/article/details/79230319 >>>
1.创建附加属性,在附加属性值改变事件中编写窗口关闭代码。
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); } }
2.创建ChildWindowViewModel 类,当需要关闭绑定了ChildWindowViewModel 类的View时,只需要改变ChildWindowViewModel 类中的ViewModel类中的DialogResult属性,只要DialogResult属性修改,就会触发第1步中创建的附加属性值改变事件。
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; }); } } }
3.在View中给附加属性绑定ChildWindowViewModel类中的DialogResult属性。
<Window x:Class="mvvm_demo_close_window.ChildWindow" ... xmlns:xc="clr-namespace:mvvm_demo_close_window" xc:DialogCloser.DialogResult="{Binding DialogResult}">