Edit this page

Override Diagram Command

This article will show you how to override the default behavior of the commands used across the RadDiagram control.

The diagram uses the DiagramCommands class and its static RoutedUICommands to execute different actions like paste, delete, copy, undo, redo, etc. To replace the default behavior of a command you can use the standart approach for binding an action to a RoutedUICommand.

The following steps describe how to override the DiagramCommands.Delete command and implement a very basic deleting process from scratch. This approach can be used to override also other commands from the DiagramCommands class or any other RoutedUICommand.

  1. Define a new CommandBinding object and register it using the CommandManager. The binding will be used to replace the default behavior of the command. You can do that in the static constructor of the window, UserControl or the application which uses the RadDiagram control.

    Example 1: Defining CommandBinding

        static MainPage()
        {
            var commandBinding = new CommandBinding(
                DiagramCommands.Delete, 
                OnDiagramDeleteCommandExecute, 
                OnDiagramDeleteCommandCanExecute);
            CommandManager.RegisterClassCommandBinding(typeof(RadDiagram), commandBinding);
        }
    
  2. Implement the OnCanExecute handler of the command. Here you can decide whether the command can be executed or not.

    Example 2: Implementing OnCanExecute

        static void OnDiagramDeleteCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            // Here you can implement additional logic that decides whether the command should be executed or not
            e.CanExecute = true;
            e.Handled = true;
        }
    
  3. Implement the OnExecute handle of the command. Here is implemented the behavior of the command. The following code shows how to create very basic delete operation.

    Example 3: Implementing OnCanExecute

        static void OnDiagramDeleteCommandExecute(object sender, ExecutedRoutedEventArgs e)
        {
            var diagram = (RadDiagram)sender;             
            while (diagram.SelectedItems.Count() > 0)
            {
                var item = diagram.SelectedItems.ElementAt(diagram.SelectedItems.Count() - 1);
                if (item is RadDiagramContainerShape)
                {
                    RemoveContainerShapeChildren(diagram, (RadDiagramContainerShape)item);                    
                }
                diagram.Items.Remove(item);
            }
        }
    
        static void RemoveContainerShapeChildren(RadDiagram diagram, RadDiagramContainerShape container)
        {
            while (container.Items.Count > 0)
            {                
                diagram.Items.Remove(container.Items[container.Items.Count - 1]);
            }         
        }
    

    See Also