Search code examples
wpfrouted-events

What am I missing with this RoutedEvent?


In a custom FrameworkElement (a Shape) I have:

public static readonly RoutedEvent DragDeltaEvent = EventManager.RegisterRoutedEvent("DragDelta", RoutingStrategy.Bubble, typeof(DragDeltaEventHandler), typeof(MyShape));
public event DragDeltaEventHandler DragDelta { add { AddHandler(DragDeltaEvent, value); } remove { RemoveHandler(DragDeltaEvent, value); } }

// xaml DataTemplate:
    <local:MyShape DragDelta="MyShape_DragDelta" />

The AddHandler above is not invoked when the shapes (in a DataTemplate) are created.
I never receive the event in code behind when I fire it in my shape by:

RaiseEvent(new DragDeltaEventArgs(...);

Solution

  • Typical code for eventhandler definition and corresponding eventarguments are:

    public class DeltaEventArgs : RoutedEventArgs
    {
            public DeltaEventArgs(double horizontalChange, double verticalChange) : base()
            {
                _horizontalChange = horizontalChange;
                _verticalChange = verticalChange;
                RoutedEvent = MyShape.DragDeltaEvent;
            }
    
            public double HorizontalChange
            {
                get { return _horizontalChange; }
            }
    
            public double VerticalChange
            {
                get { return _verticalChange; }
            }
    
            protected override void InvokeEventHandler(Delegate genericHandler, object genericTarget)
            {
                DeltaEventHandler handler = (DeltaEventHandler)genericHandler;
    
                handler(genericTarget, this);
            }
    
            private double _horizontalChange;
            private double _verticalChange;
        }
    
        public delegate void DeltaEventHandler(object sender, DeltaEventArgs e);
    

    I reused code from the frameworks Thumb class to create a kind of "thumb" shape.
    But you then cannot reuse the eventhandlers and event-arguments, because they are specifically for the Thumb class.

    When you use a regular Shape as a DataTemplate and surrond it with a regular Thumb the dragging becomes often irregular (comp. this question). Trying to repair that behaviour.