使用VisualStateManager在datatemplate中的WPF动画

时间:2012-10-09 10:59:57

标签: wpf animation datatemplate visualstatemanager

当您尝试为某些VisualStates输入DataTemplate时,这是一个非常常见的问题。

以下代码运行正常,但仅当我使用FrameworkElement时,例如自定义UserControl

<UserControl>
    ...namespaces goes here...

 <Grid x:Name="rootgrid">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="States">
                <Storyboard x:Key="Focused">
        <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="ellipse">
            <EasingColorKeyFrame KeyTime="0:0:0.1" Value="#FFE90B0B"/>
        </ColorAnimationUsingKeyFrames>
       </Storyboard>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>

        <Ellipse x:Name="ellipse"
              Width="26"
              Height="26"
              Fill="Yellow"
              SnapsToDevicePixels="True"
              Stretch="Fill"
              Stroke="Black"
              StrokeThickness="2">
            <Ellipse.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform/>
                    <TranslateTransform/>
                </TransformGroup>
            </Ellipse.RenderTransform>
        </Ellipse>
    </Grid> 

</UserControl>

但是当我尝试将代码粘贴到DataTemplate

<DataTemplate x:Key="MyDataTemplate">
   <Grid x:Name="rootgrid">
       ... Code the same as above...
    </Grid>
 </DataTemplate>

然后我申请&#34; MyDataTemplate&#34;到我的自定义元素(类,它实现了ContentTemplate依赖属性),我不能使用动画状态&#34;聚焦&#34;在那种情况下。

即使我得到一个名为&#34; rootgrid&#34;的网格对象。通过VisualTree并使用它:

VisualStateManager.GoToState(rootgrid,"Focused",true);

什么都没发生...... :(

问题是如何在VisualStates中为非DataTemplate个对象使用FrameworkElement(动画)?

1 个答案:

答案 0 :(得分:0)

答案对OP来说可能为时已晚,但对于其他任何绊倒此问题的人来说都是如此:

可以在VisualStateManager中使用DataTemplate。关键是使用包含VisualStateManager.GoToElementState的{​​{1}}来调用VisualStateManager.GoToState而不是FrameworkElement

顺便说一下,上面的XAML没有正确指定Focused的VisualStateManager,这应该改为:

VisualState