我有以下代码(它只是 ListBoxItem 的 Blend ControlTemplate 加上两个新状态和一个事件处理程序以简化示例):
xml:
<StackPanel>
<Button Click="ButtonBase_OnClick" Content="Clicle"/>
<ListBox Grid.Row="1" Margin="12,0,12,0" x:Name="list">
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border x:Name="LayoutRoot" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}" MouseLeftButtonDown="LayoutRoot_OnMouseLeftButtonDown">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver"/>
<VisualState x:Name="Disabled"/>
</VisualStateGroup>
<VisualStateGroup x:Name="SelectionStates">
<VisualState x:Name="Unselected"/>
<VisualState x:Name="Selected"/>
</VisualStateGroup>
<VisualStateGroup x:Name="Custom">
<VisualState x:Name="NotSet"/>
<VisualState x:Name="Set"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<ContentControl x:Name="ContentContainer" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
</ListBox>
</StackPanel>
然后我试图设置这些新状态之一的代码:
private void LayoutRoot_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
bool result = ExtendedVisualStateManager.GoToElementState(sender as FrameworkElement, "Set", true);
}
无论我尝试什么,我总是得到result = false
所以状态不会改变。由于我对视觉状态很陌生,我做错了什么?
编辑:
我还尝试了以下代码来使用 ListBoxItem 但它也失败了:
DependencyObject parent = VisualTreeHelper.GetParent(sender as FrameworkElement);
var a = ExtendedVisualStateManager.GoToElementState(parent as FrameworkElement, "Set", false);
编辑:
我想我在查看 VisualStateManager 时发现了问题。它检查 VisualStates 是否存在,并且当前状态被声明到 Border,而不是 ListBoxItem(检查调用 VisualStateManager.GetVisualGroups)。知道为什么吗?
提前致谢。