使用自定义事件时,EventTrigger路由事件不会触发。

3

我试图在自定义路由事件(由我定义)触发时激活一个动画。该事件称为CustomTest,定义在MyControl中。

尽管事件已被触发,但触发器并未播放动画。

XAML:

<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:gear="clr-namespace:GearWPF"
    x:Class="GearWPF.MyControl"
    x:Name="UserControl">

...

    <Grid x:Name="LayoutRoot" Background="#00000000">
        <Grid.Triggers>
            <EventTrigger RoutedEvent="gear:MyControl.CustomTest"> <!-- My custom event. -->
                <BeginStoryboard Storyboard="{StaticResource MyStoryBoard}"/>
            </EventTrigger>
        </Grid.Triggers>
    </Grid>

C#:

namespace GearWPF
{
    /// <summary>
    /// Interaction logic for MyControl.xaml
    /// </summary>
    public partial class MyControl: UserControl
    {

        // Create a custom routed event by first registering a RoutedEventID 
        // This event uses the bubbling routing strategy 
        public static readonly RoutedEvent CustomTestEvent = EventManager.RegisterRoutedEvent("CustomTest", RoutingStrategy.Bubbling, typeof(RoutedEventHandler), typeof(MyControl));

        // Provide CLR accessors for the event 
        public event RoutedEventHandler CustomTest
        {
            add { AddHandler(CustomTestEvent, value); }
            remove { RemoveHandler(CustomTestEvent, value); }
        }

        public MyControl()
        {
            this.InitializeComponent();
        }

        public void RaiseMyEvent()
        {
            RoutedEventArgs newEventArgs = new RoutedEventArgs(CustomTestEvent);
            RaiseEvent(newEventArgs);
        }
    }
}

我已经验证了当我期望时RaiseMyEvent被调用。并使用Snoop,我可以看到事件一直传递到我的控件(其中handled为“False”)。但是触发器实际上并没有启动storyboard。

我还将触发器更改为使用现有事件,当我这样做时,storyboard会被触发。这使我相信它是与我的路由事件CustomTest有关的特定问题。

    <Grid x:Name="LayoutRoot" Background="#00000000">
        <Grid.Triggers>
            <EventTrigger RoutedEvent="Mouse.MouseEnter"> <!-- This works! -->
                <BeginStoryboard Storyboard="{StaticResource MyStoryBoard}"/>
            </EventTrigger>
        </Grid.Triggers>
    </Grid>
1个回答

3
问题在于事件被触发的级别过高。我将其发送到了自定义控件,但我真正想做的是将其发送到CustomControl中的Grid内部(因为事件只会在根和源之间传递)。
    public void RaiseMyEvent()
    {
        RoutedEventArgs newEventArgs = new RoutedEventArgs(CustomTestEvent);
        LayoutRoot.RaiseEvent(newEventArgs); // This change fixes the issue.
    }

1
我在MainWindow.xaml.cs中有自己的RoutedEvent,但我的EventTrigger没有触发。你的答案帮了我大忙,因为我把它放在Grid里面,所以无法捕捉到事件! - metoyou

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接