如何动画WPF数据绑定行项目(形状)

时间:2013-02-06 13:46:09

标签: c# wpf mvvm

我正在使用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 X1X2Y1Y2TimeOffset属性。数据使用动画中的各个属性绑定到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>

0 个答案:

没有答案