1

我的问题很简单:有可能吗?

假设我想设置 a 的样式ListBoxItem,使其默认为黑色前景,选中时为蓝色,鼠标悬停时为红色。我最终得到了这样的结果:

<!-- assume the default foreground color is black -->
<ControlTemplate TargetType="ListBoxItem">
    <Grid Background="{TemplateBinding Background}">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualState x:Name="Normal"/>

                <VisualState x:Name="MouseOver">
                    <Storyboard>
                        <ColorAnimation Duration="0:0:0.2" To="Red" Storyboard.TargetName="contentControl" Storyboard.TargetProperty="(Control.Foreground).(SolidColorBrush.Color)"/>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>

            <VisualStateGroup x:Name="SelectionStates">
                <VisualState x:Name="Unselected"/>

                <VisualState x:Name="Selected">
                    <Storyboard>
                        <ColorAnimation Duration="0:0:0.2" To="Blue" Storyboard.TargetName="contentControl" Storyboard.TargetProperty="(Control.Foreground).(SolidColorBrush.Color)"/>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>

        <ContentControl x:Name="contentControl" Foreground="{TemplateBinding Foreground}" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}"/>
    </Grid>
</ControlTemplate>

问题是ListBoxItem该类已将选择状态正确放置在其自己的视觉状态组中,与鼠标悬停等常见状态分开。这意味着 aListBoxItem可以处于选中状态和鼠标悬停状态。

如果ListBoxItem选中并正确显示为蓝色,将鼠标悬停在它上面会将其恢复为黑色,因为它会转换回正常状态。

我有什么办法可以在不诉诸子类化ListBoxItem和添加我自己的自定义状态的情况下处理这个问题?我读过的所有内容都表明这是不可能的,但这对我来说似乎是可笑的限制。我错过了什么?

4

1 回答 1

3

您基本上要求前景同时为黑色和蓝色。现在这是不可能的。如果个别状态具有优先权,则可以解决此冲突,例如 MouseOver > Selected > Normal > Unselected。但它会给已经很复杂的视觉状态管理器带来不必要的复杂性。通常,这种情况可以通过添加新元素并在其中一个冲突状态组中为该元素的属性设置动画来解决。

于 2010-09-11T20:58:48.197 回答