我对这个RoutedEvent错过了什么?

时间:2014-02-21 14:15:33

标签: wpf routed-events

在自定义FrameworkElement(一个Shape)中,我有:

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" />

创建形状(在DataTemplate中)时,不会调用上面的AddHandler 当我通过以下方式解雇时,我从未收到过代码背后的事件:

RaiseEvent(new DragDeltaEventArgs(...);

1 个答案:

答案 0 :(得分:0)

事件处理程序定义和相应的事件参数的典型代码是:

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);

我重用了框架Thumb类中的代码来创建一种“拇指”形状 但是,您无法重用事件处理程序和事件参数,因为它们专门用于Thumb类。

当您使用常规Shape作为DataTemplate并使用常规Thumb进行覆盖时,拖动变得经常不规则(comp。this question)。试图修复这种行为。