Can I change the VisualState DataTemplate to ItemTemplate?

I have some controls in a DataTemplate, and I would like to control its click state behavior. I did the following when I just typed into the VisualStateManager in a DataTemplate, but it does not seem to work. I think you can understand what I'm trying to do below. Is it possible to do this inside the built-in DataTemplate tags?

<ItemsControl ItemsSource="{Binding Items}"> .... <ItemsControl.ItemTemplate> <DataTemplate> <Grid ...> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> ... <VisualState x:Name="Pressed"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderThickness" Storyboard.TargetName="GridItemBorder"> <DiscreteObjectKeyFrame KeyTime="0" Value="3"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Border x:Name="Border" ...> ... </Border> </Grid> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> 
+6
source share
1 answer

The short answer is that there is no β€œclicked” visual state for the type of control you are aiming for, so when you can refer to any state in the visual state manager, it doesn’t matter, since the control code will never put this into that state.

You can see which visual states the control supports by looking at its definition (they are declared using the TemplateVisualState attribute) or by looking at this section on MSDN .

The way here may be to use the Button (or override the [ButtonBase][2] you are writing), since it has a built-in visual state of "Pressed". You just need to write a Template control for it that provides the layouts / styles that you follow.


Edit Here is an example:

Management template (resource section). This is the control pattern for the Button control, but it is not a button. I just use it to take advantage of the functionality of the visual state of the Press.

  <ControlTemplate x:Key="MyButtonTemplate" TargetType="Button"> <Grid> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Pressed"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderThickness)" Storyboard.TargetName="GridItemBorder"> <DiscreteObjectKeyFrame KeyTime="0" Value="3"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Border x:Name="GridItemBorder" BorderBrush="Orange" BorderThickness="1" Background="White"> <ContentPresenter Content="{TemplateBinding Content}" /> </Border> </Grid> </ControlTemplate> 

Control

Define the item template as "Button", which uses the ControlTemplate above.

  <ItemsControl ItemsSource="{Binding SelectedItems}"> <ItemsControl.ItemTemplate> <DataTemplate> <Button Template="{StaticResource MyButtonTemplate}" Content="{Binding}" /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> 
+2
source

All Articles