To start using the command, you must do three things:
One: Define a command
Two: Defining the implementation of a command
Three: Create a trigger for the command
The base of a command system in WPF is a relatively simple ICommand interface with the following code:
Public interface ICommand
{
event EventHandler canexecutechanged;
BOOL CanExecute (object parameter);
void Execute (object parameter);
CanExecute is used to determine whether the command is in an executable state. Typically, a UI control can use CanExecute to enable or disable itself. In other words, the button becomes unavailable when the associated command returns false from CanExecute.
Execute is the key to the command, and when invoked, it triggers the execution of the command.
To define a new command, you can implement the ICommand interface. If you want ICommand to close the application after it is called, the code is as follows:
public class Exit:icommand {
event EventHandler canexecutechanged;
public bool CanExecute (object parameter)
{return
true;
}
public void Execute (object parameter)
{
Application.Current.Shutdown ();
}
}
To bind a menu item to the application Shutdown command, you can hook their command property to the Exit command with the following code:
<menuitem header= "_file" >
<menuitem header= "_exit" >
<MenuItem.Command>
<local: exit/>
</MenuItem.Command>
</MenuItem>
</MenuItem>
Because it is common to use commands for multiple locations, it is common to create a static field that stores commands:
public static readonly ICommand Exitcommand = new Exit ();
The advantage of this is that by using this type of ICommand field, the implementation of the exit command can be completely privatized. Now, you can mark the exit as a private class and convert the tag to a static field, as follows:
<menuitem header= "_file" >
<menuitem header= "_exit" command= "{x:static Local:WinCommand.ExitCommand}"/ >
</MenuItem>
Below we can write a template for the window by adding a button that is hooked up to the close command, and the code is as follows:
<Window.Style>
<style targettype= "window" >
<setter property= "Template" >
< setter.value>
<controltemplate targettype= "window" >
<DockPanel>
<statusbar dockpanel.dock= "Bottom" >
<StatusBarItem>
<button
command= "{x:static
Applicationcommands.close} ">Close</Button>
</StatusBarItem>
</StatusBar>
<ContentPresenter/>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Style>