我在 DataTemplate 中有一些控件,我想控制它的按下状态行为。我做了以下操作,我只是在 DataTemplate 中放入 VisualStateManager 但它似乎不起作用。我认为可以理解我在下面要做什么。是否可以在 DataTemplate 标签内进行内联?
<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>
最佳答案
简短的回答是,您所针对的控件类型没有“按下”视觉状态——因此,虽然您可以在可视状态管理器中引用任何状态,但这无关紧要,因为控件的代码永远不会把它放在进入那个状态。
您可以通过查看控件的定义(使用 TemplateVisualState
属性声明)或查看 this section on MSDN 来查看控件支持哪些视觉状态。 .
去这里的方法可能是使用 Button
(或您编写的 [ButtonBase][2]
的覆盖),因为它具有内置的“按下”视觉状态。您只需要为其编写一个控制模板,即可提供您所追求的布局/样式。
编辑 下面是一个例子:
控制模板(资源部分)。 这是 Button
的控制模板控制,但它不是一个真正的按钮。我只是用它来利用“按下”视觉状态功能。
<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>
元素控制
将项目模板定义为使用上述 ControlTemplate 的“按钮”。
<ItemsControl ItemsSource="{Binding SelectedItems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Template="{StaticResource MyButtonTemplate}" Content="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
关于silverlight - 我可以更改 ItemTemplate 中 DataTemplate 的 VisualState 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13505092/