Prash's Blog

Create Custom Routing Events in WPF May 19, 2010

Filed under: WPF — prazjain @ 10:46 pm
Tags: ,

WPF provides a ton of events in its library, but its not too tough if you have to create a custom event to support a specific scenario.
In a small example below we will create a custom event that would sort the text we enter in the textbox.
Screen before and after the command execution :

  • Create a new WPF project, name it CustomEvents.
  • Copy paste the XAML below in Window1.xaml file

<StackPanel>
 <TextBox Name="textBox" Margin="10,10" />
 <Button Name="btnSort" HorizontalAlignment="Center" Padding="10,3" FontWeight="Bold" Margin="10,3">Sort</Button>
 </StackPanel>

  • Create a custom command for our use:

/// <summary>
 /// Class that holds the custom command(s)
 /// </summary>
 public class SortCommand
 {
 /// <summary>
 /// Actual command object
 /// </summary>
 private static RoutedUICommand sortCommand;

 /// <summary>
 /// Property exposing the command object
 /// </summary>
 public static RoutedCommand Sort
 {
 get { return sortCommand; }
 }

 /// <summary>
 /// Static constructor initializing the input gestures that should invoke the custom command
 /// </summary>
 static SortCommand()
 {
 InputGestureCollection gestures = new InputGestureCollection();
 gestures.Add(new KeyGesture(Key.S, ModifierKeys.Control, "Control-S"));
 sortCommand = new RoutedUICommand("Sort Command", "Sort", typeof(SortCommand), gestures);
 }
 }

  • Now we have created a custom command and we have a UI in place. Now linkup the command object and the UI. Assuming you have not renamed Window1.xaml, paste the code below into your Window1.xaml.cs.

/// <summary>
 /// Interaction logic for Window1.xaml
 /// </summary>
 public partial class Window1 : Window
 {
 public Window1()
 {
 InitializeComponent();
// attach the command to the button so the command can be invoked on button click
 btnSort.Command = SortCommand.Sort;
// create a command binding and attach actual handlers to the command.
 CommandBinding binding = new CommandBinding();
 binding.Command = SortCommand.Sort;
 binding.CanExecute += new CanExecuteRoutedEventHandler(binding_CanExecute);
 binding.Executed += new ExecutedRoutedEventHandler(binding_Executed);
//add the command binding to window, so it would handle the execute event
 this.CommandBindings.Add(binding);
 }

 void binding_Executed(object sender, ExecutedRoutedEventArgs e)
 {
 char[] contents = textBox.Text.ToCharArray();
 Array.Sort(contents);
 textBox.Text = new string(contents);
 }

 void binding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
 {
// we sort only if there is some text
 e.CanExecute = textBox.Text.Length > 0;
 }
 }

When the button is clicked as there is no command binding associated with the Sort command there, the event is routed up the element tree
where the window handles the executed event.

Advertisements