在事件触发器中处理自定义RoutedEvent

时间:2017-05-19 15:25:42

标签: c# wpf events routed-events

我有以下树 MainWindow - >自定义UserControl - > GroupBox - >视框

我已将自定义路由事件添加到UserControl,如下:

  public static readonly RoutedEvent ConnectedEvent =
        EventManager.RegisterRoutedEvent("Connected", RoutingStrategy.Tunnel,
        typeof(RoutedEventHandler), typeof(IQMasterControl));

    public event RoutedEventHandler Connected
    {
        add { AddHandler(IQMasterControl.ConnectedEvent, value); }
        remove { RemoveHandler(IQMasterControl.ConnectedEvent, value); }
    }

事件的调用如下:

 _masterViewModel.Connected += delegate ()
        {
            RoutedEventArgs ea = new RoutedEventArgs(IQMasterControl.ConnectedEvent, this);
            this.RaiseEvent(ea);
        };

我想在ViewBox上运行一些动画"已连接"使用事件触发器的事件:

<Viewbox VerticalAlignment="Center"
                      Child="{StaticResource PDataIco}"
                      RenderTransformOrigin="0.5, 0.5" Stretch="Uniform">
                        <Viewbox.RenderTransform>
                            <!--  the transform a name tells the framework not to freeze it  -->
                            <RotateTransform x:Name="noFreeze" />
                        </Viewbox.RenderTransform>
                        <Viewbox.Triggers>
                            <EventTrigger RoutedEvent="local:IQMasterControl.Connected">
                                <BeginStoryboard>
                                    <Storyboard>
                                        <DoubleAnimation RepeatBehavior="Forever" Storyboard.TargetProperty="(Rectangle.RenderTransform).(RotateTransform.Angle)" To="360" Duration="0:0:1" />
                                    </Storyboard>
                                </BeginStoryboard>
                            </EventTrigger>
                        </Viewbox.Triggers>
                    </Viewbox>

我已检查过该事件已被引发,但ViewBox似乎没有收到该事件。因此,没有动画启动。

如果我将EventTrigger的RoutedEvent属性更改为另一个(f.e。已加载),则动画可以正常工作。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:3)

您正在提升event的{​​{1}}。

UserControl没有提出。

有两种方法:

两者都需要为ViewBox添加名称:

ViewBox

1.为<Viewbox VerticalAlignment="Center" x:Name="ViewBox" Child="{StaticResource PDataIco}" RenderTransformOrigin="0.5, 0.5" Stretch="Uniform"> <Viewbox.RenderTransform> <!-- the transform a name tells the framework not to freeze it --> <RotateTransform x:Name="noFreeze" /> </Viewbox.RenderTransform> <Viewbox.Triggers> <EventTrigger RoutedEvent="local:IQMasterControl.Connected"> <BeginStoryboard> <Storyboard> <DoubleAnimation RepeatBehavior="Forever" Storyboard.TargetProperty="(Rectangle.RenderTransform).(RotateTransform.Angle)" To="360" Duration="0:0:1" /> </Storyboard> </BeginStoryboard> </EventTrigger> </Viewbox.Triggers> </Viewbox>

提高它
ViewBox

2.在_masterViewModel.Connected += delegate () { RoutedEventArgs ea = new RoutedEventArgs(IQMasterControl.ConnectedEvent, this); ViewBox.RaiseEvent(ea); }; 中处理它:

UserControl