Adding Visual States to a Data Template in Windows

2019-04-09 22:06发布

问题:

I am trying to add a Mouse Over effect to my Windows 8 application. Specifically I'm trying to add it to DataTemplates bound to a GridView. However, Currently, nothing is happening, I've tried to follow the Microsoft tutorials but most of those are either out of date or for different versions of XAML.

My code looks like this:

<DataTemplate x:Key="GameTileTemplate">
    <Grid x:Name="grid" Width="173" Height="173" RenderTransformOrigin="0.5,0.5" >
        <Grid.Clip>
            <RectangleGeometry Rect="0,0,173,173"/>
        </Grid.Clip>
        <Image Grid.RowSpan="3" Stretch="UniformToFill"/>
        <Grid x:Name="DataPanel" Margin="-173,0,0,0" Grid.RowSpan="3" RenderTransformOrigin="0.5,0.5" Width="346" HorizontalAlignment="Left" VerticalAlignment="Top" Height="173">
            <!--There is more here-->
        </Grid>
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStateGroup">
                <VisualState x:Name="Normal" />
                <VisualState x:Name="PointerEntered">
                    <Storyboard>
                        <DoubleAnimation From="1" To="0" Duration="00:00:02" 
                             Storyboard.TargetName="DataPanel" 
                             Storyboard.TargetProperty="Opacity">
                        </DoubleAnimation>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    </Grid>
</DataTemplate>

The Opacity of my DataPanel does not change. Do I need some other code somewhere? The Microsoft Tutorial was for a ControlTemplate, is this causing the error since my Template is a DataTemplate?

回答1:

Xaml you provided in your question is not going to work on its own. Simply defining visual states is not enough. You also need some kind of code to call VisualStateManager.GoToState.

In your particular case solution is not to add visual states to DataTemplate, but to create custom template for GridViewItem. In general GridViewItem is responsible for decorating elements inside the GridView with common pointer, selection, drag and drop states.



回答2:

Add UserControl balise it works, (don't know why)

 <DataTemplate x:Key="GameTileTemplate">
<UserControl>
<Grid x:Name="grid" Width="173" Height="173" RenderTransformOrigin="0.5,0.5" >
        <Grid.Clip>
....

...
 </VisualStateManager.VisualStateGroups>
    </Grid>
</UserControl>
</DataTemplate>