RaiseEvent不会触发自定义RoutedEvent

时间:2018-04-05 12:07:00

标签: c# wpf

这是我第一次尝试定义自己的RoutedEvent。当我调试这个项目时,只要我将鼠标悬停在椭圆形状上,就会到达OnMouseMove,但RaiseEvent什么都不做。它甚至无法进入RaiseEvent以查看错误(调试器只是跳过了)。

控制:

using System;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
using System.Windows.Input;
using System.Windows.Controls.Primitives;

namespace TestTrailer2
{
    public class Trailer2: Control
    {
        public static readonly RoutedEvent DragDeltaEvent;

        public event DragDeltaEventHandler DragDelta 
        {
            add {AddHandler(Trailer2.DragDeltaEvent, value);}
            remove {RemoveHandler(Trailer2.DragDeltaEvent, value);}
        }

        static Trailer2()
        {
            Trailer2.DragDeltaEvent = EventManager.RegisterRoutedEvent("DragDelta", RoutingStrategy.Bubble, typeof(DragDeltaEventHandler), typeof(Trailer2));
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            RaiseEvent(new DragDeltaEventArgs(0, 0));
        }
    }
}

代码背后:

using System;
using System.Windows;

namespace TestTrailer2
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        void Trailer2_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            throw new NotImplementedException();
        }
    }
}

标记:

<Window x:Class="TestTrailer2.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:TestTrailer2"
    Title="TestTrailer2" Height="300" Width="300">
    <Window.Resources>
        <Style TargetType="{x:Type local:Trailer2}">
            <Setter Property="RenderTransformOrigin" Value="0.5,0.5"/>
            <Setter Property="Cursor" Value="Hand"/>
            <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:Trailer2}">
                    <Ellipse Width="100" Height="100" Fill="#AAD0D0DD"/>
                </ControlTemplate>
            </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <local:Trailer2 DragDelta="Trailer2_DragDelta">
    </local:Trailer2>
</Window>

1 个答案:

答案 0 :(得分:1)

问题是您正在重复使用最初属于另一个路由事件DragDeltaEventArgs的{​​{1}}。所以当你这样做时:

Thumb.DragDeltaEvent

真正提出的是RaiseEvent(new DragDeltaEventArgs(0, 0)); ,而不是您的自定义事件(请注意,您没有说明要在哪个地方举起哪个事件)。该事件在Thumb.DragDeltaEvent构造函数中是硬编码的。

如果您想继续重复使用它 - 您需要明确说明您的自定义事件:

DragDeltaEventArgs

或者只使用自定义路由事件参数。