Ellipse使用Canvas模板在ItemsControl中移动动画

时间:2011-03-28 23:16:25

标签: c# wpf xaml animation mvvm

使用DoubleAnimation,附加属性Canvas.Left应逐渐设置为100:

        <Ellipse Width="30" Height="30" Fill="Purple">
            <Ellipse.Triggers>
                <EventTrigger RoutedEvent="Ellipse.Loaded">
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation Duration="0:0:5" Storyboard.TargetProperty="(Canvas.Left)" To="100" RepeatBehavior="Forever" />
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Ellipse.Triggers>
        </Ellipse>

此Ellipse(我的viewmodel的datatemplate的一部分)通过ItemsSource绑定到ItemsControl:

<ItemsControl ItemsSource="{Binding Components}">

    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas Background="Beige" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="Canvas.Left" Value="{Binding X}" />
            <Setter Property="Canvas.Top" Value="{Binding Y}" />
        </Style>
    </ItemsControl.ItemContainerStyle>


</ItemsControl>

但是,加载椭圆时会发生以下异常:

Cannot animate the 'Left' property on a 'System.Windows.Shapes.Ellipse' using a 'System.Windows.Media.Animation.DoubleAnimation'.

但是动画的targetproperty被指定为“Canvas.Left”而不是“Left”?

1 个答案:

答案 0 :(得分:1)

您需要初始化Canvas.Left才能使DoubleAnimation工作:

<Ellipse Width="30" Height="30" Fill="Purple" Canvas.Left="0">