Implementing “close window” command with MVVM

后端 未结 12 1702
既然无缘
既然无缘 2020-12-05 09:31

So my first attempt did everything out of the code behind, and now I\'m trying to refactor my code to use the MVVM pattern, following the guidance of the MVVM in the box inf

12条回答
  •  半阙折子戏
    2020-12-05 09:59

    I do it by creating a attached property called DialogResult:

    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 && (bool?)e.NewValue == true) 
                    window.Close();
        }
    
        public static void SetDialogResult(Window target, bool? value)
        {
            target.SetValue(DialogResultProperty, value);
        }
    }
    

    then write this to you XAML, in the window tag

    WindowActions:DialogCloser.DialogResult="{Binding Close}"
    

    finally in the ViewModel

        private bool _close;
        public bool Close
        {
            get { return _close; }
            set
            {
                if (_close == value)
                    return;
                _close = value;
                NotifyPropertyChanged("Close");
            }
        }
    

    if you change the Close to true, the window will be closed

    Close = True;
    

提交回复
热议问题