WPF以编程方式创建事件触发器

时间:2018-08-29 13:03:51

标签: wpf colors eventtrigger

我有一块画布,我以编程方式添加了更多形状。对于一种形状(Path),我想添加一种填充颜色,该颜色每秒钟都会闪烁一次(从红色变为蓝色,然后从蓝色变为红色)。 我从xaml找到了一个有关如何执行此操作的示例:

<Ellipse Fill="Red">
<Ellipse.Triggers>
    <EventTrigger RoutedEvent="Ellipse.Loaded">
        <EventTrigger.Actions>
            <BeginStoryboard>
                <Storyboard>
                    <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Ellipse.Fill).(SolidColorBrush.Color)"
                                                  Duration="0:0:2"
                                                  FillBehavior="HoldEnd"
                                                  RepeatBehavior="Forever">
                        <ColorAnimationUsingKeyFrames.KeyFrames>
                            <DiscreteColorKeyFrame KeyTime="0:0:0" Value="Red"/>
                            <DiscreteColorKeyFrame KeyTime="0:0:1" Value="Blue"/>
                        </ColorAnimationUsingKeyFrames.KeyFrames>
                    </ColorAnimationUsingKeyFrames>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger.Actions>                    
    </EventTrigger>
</Ellipse.Triggers>

但是当我从代码中执行此操作时,我收到一个ArgumentNullException:“ {”值不能为空。\ r \ n参数名称:routedEvent“}”

这是我的代码:

 var sheetPath = new Path
        {
            Stroke = Brushes.Black,
            Fill = !isSelectedSheet ? Brushes.MediumSlateBlue : GetInvertedColor(Brushes.MediumSlateBlue),
            StrokeThickness = _lineWidth,
            HorizontalAlignment = HorizontalAlignment.Left,
            VerticalAlignment = VerticalAlignment.Center,
            Data = CreatePathGeometry(contour, height)
        };

        var colorAnimationUsingKeyFrames = new ColorAnimationUsingKeyFrames
        {
            Duration = new Duration(new TimeSpan(0, 0, 0, 300)),
            RepeatBehavior = RepeatBehavior.Forever,
            FillBehavior = FillBehavior.HoldEnd
        };

        colorAnimationUsingKeyFrames.KeyFrames.Add(new DiscreteColorKeyFrame
        {
            KeyTime = KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 100)),
            Value = Colors.Red
        });
        colorAnimationUsingKeyFrames.KeyFrames.Add(new DiscreteColorKeyFrame
        {
            KeyTime = KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 200)),
            Value = Colors.Blue
        });

        var storyboard = new Storyboard();
        storyboard.Children.Add(colorAnimationUsingKeyFrames);

        Storyboard.SetTargetProperty(storyboard.Children[0], new PropertyPath("(Path.Fill).(SolidColorBrush.Color)"));
        var beginStoryboard = new BeginStoryboard();

        beginStoryboard.Storyboard = storyboard;

        var eventTrigger = new EventTrigger();
        eventTrigger.Actions.Add(beginStoryboard);

        sheetPath.Triggers.Add(eventTrigger);

        canvas.Children.Add(sheetPath);

1 个答案:

答案 0 :(得分:1)

设置RoutedEvent的{​​{1}}属性:

EventTrigger