At the beginning, it was also a little difficult for me to understand how this works, so I wanted to publish a better explanation of what is actually happening.
According to my research, the best way to deal with such things is to use Command Bindings. What happens is the “Message”, transmitted to everyone in the program. So you need to use CommandBinding . Essentially, it says, "When you hear this message, do it."
So, in the question, the user is trying to close the window. The first thing we need to do is configure our functions, which will be called when the SystemCommand.CloseWindowCommand broadcasts. If desired, you can assign a function that determines whether the command should be executed. An example would be closing a form and checking if the user has saved.
MainWindow.xaml.cs (or other code)
void CloseApp( object target, ExecutedRoutedEventArgs e ) { this.Close(); } void CloseAppCanExecute( object sender, CanExecuteRoutedEventArgs e ) { e.CanExecute = true; }
Now we need to configure the “Connection” between SystemCommands.CloseWindowCommand and CloseApp and CloseAppCanExecute
MainWindow.xaml (or anything that implements CommandBindings)
<Window.CommandBindings> <CommandBinding Command="SystemCommands.CloseWindowCommand" Executed="CloseApp" CanExecute="CloseAppCanExecute"/> </Window.CommandBindings>
You can omit CanExecute if you know that the command should always be executed. Save may be a good example depending on the application. Here is an example:
<Window.CommandBindings> <CommandBinding Command="SystemCommands.CloseWindowCommand" Executed="CloseApp"/> </Window.CommandBindings>
Finally, you must tell UIElement to send the CloseWindowCommand command.
<Button Command="SystemCommands.CloseWindowCommand">
This is actually a very simple thing, just make the connection between the Command and the actual function Execute, then tell Control to send the command to the rest of your program, saying: "Ok, everyone performs your functions for the CloseWindowCommand command."
Actually, this is a very good way to pass this, because you can fully use the executable function without having a shell like you, for example, using WinForms (using ClickEvent and calling a function in an event function), for example:
protected override void OnClick(EventArgs e){ }
In WPF, you attach a function to a command and tell UIElement to execute the function attached to the command.
Hope this clarifies the situation ...