The easiest way is to implement ButtonClick
event handler and invoke Window.Close()
method, but how doing this through a Command
binding?
相关问题
- VNC control for WPF application
- WPF Binding from System.Windows.SystemParameters.P
- XAML: Applying styles to nested controls
- How can I add a horizontal line (“goal line”) for
- How to properly change a resource dictionary
In the beginning I was also having a bit of trouble figuring out how this works so I wanted to post a better explanation of what is actually going on.
According to my research the best way to handle things like this is using the Command Bindings. What happens is a "Message" is broadcast to everything in the program. So what you have to do is use the
CommandBinding
. What this essentially does is say "When you hear this Message do this".So in the Question the User is trying to Close the Window. The first thing we need to do is setup our Functions that will be called when the
SystemCommand.CloseWindowCommand
is broadcast. Optionally you can assign a Function that determines if 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-Behind)
Now we need to setup the "Connection" between the
SystemCommands.CloseWindowCommand
and theCloseApp
andCloseAppCanExecute
MainWindow.xaml (Or anything that implements CommandBindings)
You can omit the CanExecute if you know that the Command should be able to always be executed Save might be a good example depending on the Application. Here is a Example:
Finally you need to tell the UIElement to send out the CloseWindowCommand.
Its actually a very simple thing to do, just setup the link between the Command and the actual Function to Execute then tell the Control to send out the Command to the rest of your program saying "Ok everyone run your Functions for the Command CloseWindowCommand".
This is actually a very nice way of handing this because, you can reuse the Executed Function all over without having a wrapper like you would with say WinForms (using a ClickEvent and calling a function within the Event Function) like:
In WPF you attach the Function to a Command and tell the UIElement to execute the Function attached to the Command instead.
I hope this clears things up...