Commanding with C1Toolbar (WPF Tutorial) > Part 2: Creating Custom Commands |
If the commands in the command library classes do not meet your needs, then you can create your own commands. You create a custom command by implementing the ICommand Interface. WPF provides a specific implementation named RoutedCommand (and RoutedUICommand), which defines a command routed through the element tree.
The following steps show how to add a custom command to C1Toolbar using a RoutedCommand.
public static RoutedCommand ClearCommand = new RoutedCommand();
C# |
Copy Code
|
---|---|
// performs logic for ClearCommand private void ExecutedClearCommand(object sender, ExecutedRoutedEventArgs e) { textBox1.Clear(); } |
C# |
Copy Code
|
---|---|
// only returns true if the textbox has text. private void CanExecuteClearCommand(object sender, CanExecuteRoutedEventArgs e) { if (textBox1.Text.Length > 0) { e.CanExecute = true; } else { e.CanExecute = false; } } |
C# |
Copy Code
|
---|---|
CommandBinding customCommandBinding = new CommandBinding(ClearCommand, ExecutedClearCommand, CanExecuteClearCommand); // attach CommandBinding to root element this.CommandBindings.Add(customCommandBinding); |
XAML |
Copy Code
|
---|---|
<c1:C1ToolbarGroup Header="Application"> <c1:C1ToolbarButton LabelTitle="Clear Text" Command="{x:Static local:MainWindow.ClearCommand}" LargeImageSource="/Resources/clear.png"/> </c1:C1ToolbarGroup> |