我正在使用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建议的解决方案 - 引入一个“模型”类,代表Line
X1
,X2
,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>