Routed command
Routed command can route (bubble/ tunnel) through the element hierarchy. Routed Command implements ICommand interface. It allows attaching input gestures like Mouse input and Keyboard shortcuts. Its source can be decoupled from target. WPF provides more than 100 built in commands. These commands can be integrated to WPF controls which have command properties like button, MenuItem, etc. EditingCommand, ComponentCommand, NavigationCommand, AplicationCommand are some of the classes which organize and expose built in commands.
You can create customized Routed commands by implementing ICommand.
You need to create static instance of type RoutedCommand. Then you need to implement _CanExecute and _Executed for the same.
XAML
- <Window.CommandBindings>
- <CommandBinding Command="{x:Static local:CustomRoutedCommand.MyCommand}" Executed="CommandBinding_Executed" CanExecute="CommandBinding_CanExecute" /> </Window.CommandBindings>
- <Grid>
- <Button Command="{x:Static local:CustomRoutedCommand.MyCommand}" Name="myButton" Content="Click Me!" Width="150" Height="40" />
- </Grid>
Code behind
- public static RoutedCommand MyCommand = new RoutedCommand("MyCommand", typeof(CustomRoutedCommand));
- void CustomRoutedCommand_Loaded(object sender, RoutedEventArgs e) {
- MyCommand.InputGestures.Add(new KeyGesture(Key.C, ModifierKeys.Alt));
- }
- private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
- //Return true or false based on command availablity.
- e.CanExecute = true;
- }
- private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) {
- //Write custom logic
- MessageBox.Show("My Command executed...");
- }
Now in the above example, when the user clicks on ‘ClickMe’ button it will execute MyCommand and display Messagebox and also when ALT + D key is pressed the command will execute.

pallavi morePosted Aug 3, 2018, 6:16 AM
#region SaveProject Command private Command _saveProjectCommand; public Command SaveProjectCommand { get { return _saveProjectCommand ?? (_saveProjectCommand = new Command(SaveProject)); } } private void SaveProject() { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "XML File|*.xml"; saveFileDialog1.Title = "Save XML File"; saveFileDialog1.ShowDialog(); if (saveFileDialog1.FileName != "") { FileStream fs = (FileStream)saveFileDialog1.OpenFile(); new XmlSerializer(typeof(DiagramData)).Serialize(fs, dd); fs.Close(); } } #endregion ...i wrote this code for save object but if i want to save object without using serialization what can i do
Former memberPosted Jun 23, 2017, 5:47 AM
Nice one. i have few requests that please write a article on MVVM with WPF for beginner perspective. also write article on agile scrum in real life scenario like how we can do agile scrum with TFS and also DevOps. i believe you redirect reader to right direction. thanks.