How to bind Close command to a button

前端 未结 7 1260
时光说笑
时光说笑 2020-11-30 19:09

The easiest way is to implement ButtonClick event handler and invoke Window.Close() method, but how doing this through a Command bindi

7条回答
  •  悲&欢浪女
    2020-11-30 19:45

    One option that I've found to work is to set this function up as a Behavior.

    The Behavior:

        public class WindowCloseBehavior : Behavior
    {
        public bool Close
        {
            get { return (bool) GetValue(CloseTriggerProperty); }
            set { SetValue(CloseTriggerProperty, value); }
        }
    
        public static readonly DependencyProperty CloseTriggerProperty =
            DependencyProperty.Register("Close", typeof(bool), typeof(WindowCloseBehavior),
                new PropertyMetadata(false, OnCloseTriggerChanged));
    
        private static void OnCloseTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var behavior = d as WindowCloseBehavior;
    
            if (behavior != null)
            {
                behavior.OnCloseTriggerChanged();
            }
        }
    
        private void OnCloseTriggerChanged()
        {
            // when closetrigger is true, close the window
            if (this.Close)
            {
                this.AssociatedObject.Close();
            }
        }
    }
    

    On the XAML Window, you set up a reference to it and bind the Behavior's Close property to a Boolean "Close" property on your ViewModel:

    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    
        
    
    

    So, from the View assign an ICommand to change the Close property on the ViewModel which is bound to the Behavior's Close property. When the PropertyChanged event is fired the Behavior fires the OnCloseTriggerChanged event and closes the AssociatedObject... which is the Window.

提交回复
热议问题