WPF MVVM: How to close a window

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

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


21条回答
  •  遥遥无期
    2020-12-04 08:41

    I'd personally use a behaviour to do this sort of thing:

    public class WindowCloseBehaviour : Behavior
    {
        public static readonly DependencyProperty CommandProperty =
          DependencyProperty.Register(
            "Command",
            typeof(ICommand),
            typeof(WindowCloseBehaviour));
    
        public static readonly DependencyProperty CommandParameterProperty =
          DependencyProperty.Register(
            "CommandParameter",
            typeof(object),
            typeof(WindowCloseBehaviour));
    
        public static readonly DependencyProperty CloseButtonProperty =
          DependencyProperty.Register(
            "CloseButton",
            typeof(Button),
            typeof(WindowCloseBehaviour),
            new FrameworkPropertyMetadata(null, OnButtonChanged));
    
        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }
    
        public object CommandParameter
        {
            get { return GetValue(CommandParameterProperty); }
            set { SetValue(CommandParameterProperty, value); }
        }
    
        public Button CloseButton
        {
            get { return (Button)GetValue(CloseButtonProperty); }
            set { SetValue(CloseButtonProperty, value); }
        }
    
        private static void OnButtonChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var window = (Window)((WindowCloseBehaviour)d).AssociatedObject;
            ((Button) e.NewValue).Click +=
                (s, e1) =>
                {
                    var command = ((WindowCloseBehaviour)d).Command;
                    var commandParameter = ((WindowCloseBehaviour)d).CommandParameter;
                    if (command != null)
                    {
                        command.Execute(commandParameter);                                                      
                    }
                    window.Close();
                };
            }
        }
    

    You can then attach this to your Window and Button to do the work:

    
        
            
        
        
            
        
    
    

    I've added Command and CommandParameter here so you can run a command before the Window closes.

提交回复
热议问题