我正在使用 MVVM,绑定到ObservableCollection<Shape>
(DrawingInstructions) 并希望Line
为添加的形状设置动画。
各条线应以DoubleAnimation
某种方式从 (X1,Y1) 到 (X2,Y2) 绘制。
我已经尝试过以下变体,但它不起作用。
<ItemsControl ItemsSource="{Binding Path=DrawingInstructions}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate >
<Canvas>
:
</Canvas>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.Triggers>
<EventTrigger RoutedEvent="Binding.TargetUpdated">
<BeginStoryboard>
<Storyboard >
<DoubleAnimation Duration="0:0:2" Storyboard.TargetName="CurrentLine" Storyboard.TargetProperty="Position" From="{Binding Path=X1}" To="{Binding Path=X2}"/>
<DoubleAnimation Duration="0:0:2" Storyboard.TargetName="CurrentLine" Storyboard.TargetProperty="Position" From="{Binding Path=Y1}" To="{Binding Path=Y2}"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</ItemsControl.Triggers>
Viewmodel 包含命名要添加到绘图指令的 Line 的代码。
var line = new Line
{
X1 = currentSituation.Position.X,
Y1 = currentSituation.Position.Y,
X2 = newSituation.Position.X,
Y2 = newSituation.Position.Y,
Name = "CurrentLine",
Stroke = brush,
StrokeThickness = 2
};
drawingInstructions.Add(line);
更新:
@Nico 建议的解决方案有效——引入一个“模型”类,表示一个with Line
、X1
、X2
和properties 。数据绑定到使用动画中的各个属性:Y1
Y2
TimeOffset
ObservableCollection<MyModelClass>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Line Name="CurrentLine" X1="{Binding X1}" Y1="{Binding Y1}" X2="{Binding X1}" Y2="{Binding Y1}" Stroke="Black" StrokeThickness="2">
<Line.Triggers>
<EventTrigger RoutedEvent="Loaded">
<BeginStoryboard>
<Storyboard >
<DoubleAnimation Storyboard.TargetName="CurrentLine" Storyboard.TargetProperty="X2" BeginTime="{Binding Path=TimeOffset}" From="{Binding Path=X1}" To="{Binding Path=X2}"/>
<DoubleAnimation Storyboard.TargetName="CurrentLine" Storyboard.TargetProperty="Y2" BeginTime="{Binding Path=TimeOffset}" From="{Binding Path=Y1}" To="{Binding Path=Y2}"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Line.Triggers>
</Line>
</DataTemplate>
</ItemsControl.ItemTemplate>