Catch DesignerItem-Event on DesignerCanvas

In your application almost for sure the moment comes, when you want to react on either a click or doubleclick of the DesignerItem. Normally you’ll want to catch these events on the DesignerCanvas for all DesignerItems. This article will show you how to react on a double-click on the designeritem. To do so, we need to

  • Register a routed event in the DesignerItem-Class
  • Register the attached event on the DesignerCanvas
  1. Open the file DesignerItem.cs
  2. Add the following code anywhere in the DesignerItem-Class:
    // Event registration
    public static readonly RoutedEvent DoubleClickEvent = EventManager.RegisterRoutedEvent("DoubleClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(DesignerItem));
    public event RoutedEventHandler DoubleClick
        add { AddHandler(DoubleClickEvent, value); }
        remove { RemoveHandler(DoubleClickEvent, value); }
    // Raising the event
    protected override void OnMouseDoubleClick(MouseButtonEventArgs e) 
        RoutedEventArgs args = new RoutedEventArgs(DoubleClickEvent, this); 
  3. As the intellisense does not recognize the event automatically, we first need to provide the doubleclick-event code in Window1.xaml.cs
    private void DesignerItem_DoubleClick(object sender, RoutedEventArgs e)
       DesignerItem designerItem = e.Source as DesignerItem;
  4. Register the method DesignerItem_DoubleClick as attached event in Window1.xaml, like in the following snippet:
    <!-- Designer -->
    <GroupBox Header="Diagram" Grid.Column="1" Margin="3,0,0,0">
        <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <s:DesignerCanvas Focusable="true" x:Name="MyDesigner"
                    Background="{StaticResource WindowBackgroundBrush}"
                    Margin="10" FocusVisualStyle="{x:Null}"
                    ContextMenu="{StaticResource DesignerCanvasContextMenu}"/>

The easyiest way to test it is, if you set a break-point in the doubleclick-code, start the diagram designer, drag an item on the designer and doubleclick it. Then the debugger should stop on the break-point. There you go.