【发布时间】:2018-08-29 13:03:50
【问题描述】:
我有一个画布,可以在其中以编程方式添加更多形状。对于其中一个形状(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:"{"Value cannot be null.\r\nParameter name: 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);
【问题讨论】:
-
“我以编程方式添加更多形状的画布” - 不要那样做。改用 ItemsControl,如所示,例如这里:stackoverflow.com/a/40190793/1136211
-
我做不到。我必须动态创建它们。我也有文字,有些形状是重叠的,我必须解析一些对象才能创建它们......
-
无论如何,你对我的问题有什么建议吗?或者至少我的代码有什么问题,为什么我会得到那个异常?
-
这并不意味着您不能使用 ItemsControl。您仍然可以添加文本并具有重叠的形状,当然您也可以解析视图模型对象。 MVVM 迟早会成为更好的方法。
-
我的依赖属性有问题,这就是我选择 MPV 模式的方式。
标签: wpf colors eventtrigger