WPF MVVM: How to close a window

后端 未结 21 1769
后悔当初
后悔当初 2020-12-04 08:19

I have a Button that closes my window when it\'s clicked:


21条回答
  •  死守一世寂寞
    2020-12-04 08:59

    As someone commented, the code I have posted is not MVVM friendly, how about the second solution?

    1st, not MVVM solution (I will not delete this as a reference)

    XAML:

    
    

    ViewModel:

    public ICommand OkCommand
    {
        get
        {
            if (_okCommand == null)
            {
                _okCommand = new ActionCommand(DoOk, CanDoOk);
            }
            return _okCommand ;
        }
    }
    
    void DoOk(Window win)
    {
        // Your Code
        win.DialogResult = true;
        win.Close();
    }
    
    bool CanDoOk(Window win) { return true; }
    

    2nd, probably better solution: Using attached behaviours

    XAML

    View Model

    public ICommand OkCommand
    {
        get { return _okCommand; }
    }
    

    Behaviour Class Something similar to this:

    public static class CloseOnClickBehaviour
    {
        public static readonly DependencyProperty IsEnabledProperty =
            DependencyProperty.RegisterAttached(
                "IsEnabled",
                typeof(bool),
                typeof(CloseOnClickBehaviour),
                new PropertyMetadata(false, OnIsEnabledPropertyChanged)
            );
    
        public static bool GetIsEnabled(DependencyObject obj)
        {
            var val = obj.GetValue(IsEnabledProperty);
            return (bool)val;
        }
    
        public static void SetIsEnabled(DependencyObject obj, bool value)
        {
            obj.SetValue(IsEnabledProperty, value);
        }
    
        static void OnIsEnabledPropertyChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs args)
        {
            var button = dpo as Button;
            if (button == null)
                return;
    
            var oldValue = (bool)args.OldValue;
            var newValue = (bool)args.NewValue;
    
            if (!oldValue && newValue)
            {
                button.Click += OnClick;
            }
            else if (oldValue && !newValue)
            {
                button.PreviewMouseLeftButtonDown -= OnClick;
            }
        }
    
        static void OnClick(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            if (button == null)
                return;
    
            var win = Window.GetWindow(button);
            if (win == null)
                return;
    
            win.Close();
        }
    
    }
    

提交回复
热议问题