Wpf 自定义样式列表框-如何保持所选项目的样式?
我有一个样式化的列表框。当鼠标悬停在上方和选中时,列表框项目会更改颜色。悬停并选择“工作正常”。但是,当选择一个项目,然后将鼠标从其上取下并返回到悬停状态时,会导致该项目返回到悬停/未选中状态,即使它仍然处于选中状态。如何将listboxitem保持在“选定”视觉状态Wpf 自定义样式列表框-如何保持所选项目的样式?,wpf,silverlight,xaml,listbox,styles,Wpf,Silverlight,Xaml,Listbox,Styles,我有一个样式化的列表框。当鼠标悬停在上方和选中时,列表框项目会更改颜色。悬停并选择“工作正常”。但是,当选择一个项目,然后将鼠标从其上取下并返回到悬停状态时,会导致该项目返回到悬停/未选中状态,即使它仍然处于选中状态。如何将listboxitem保持在“选定”视觉状态 <Style x:Name="myListBoxItemStyle" TargetType="ListBoxItem"> <Setter Property="Template"> &
<Style x:Name="myListBoxItemStyle" TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border x:Name="myBorder" CornerRadius="5" BorderThickness="3" Background="#FF292121" Margin="0">
<Grid HorizontalAlignment="Stretch">
<ContentPresenter Content="{TemplateBinding Content}" Margin="5,0,5,0" />
</Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver">
<Storyboard>
<ColorAnimation Storyboard.TargetName="myBorder" Storyboard.TargetProperty="(Background).(SolidBrush.Color)" Duration="00:00:00.2" To="#FF949290" />
</Storyboard>
</VisualState>
<VisualState x:Name="Disabled"/>
</VisualStateGroup>
<VisualStateGroup x:Name="SelectionStates">
<VisualState x:Name="Unselected" />
<VisualState x:Name="Selected">
<Storyboard>
<ColorAnimation Storyboard.TargetName="myBorder" Storyboard.TargetProperty="(Background).(SolidBrush.Color)" Duration="00:00:00.2" To="#FF949290" />
</Storyboard>
</VisualState>
<VisualState x:Name="SelectedUnfocused"/>
</VisualStateGroup>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="myListBoxStyle" TargetType="ListBox">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Margin" Value="0"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="ItemContainerStyle" Value="{StaticResource myListBoxItemStyle}"/>
<Setter Property="VerticalAlignment" Value="Bottom"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBox">
<Grid Margin="0">
<ItemsPresenter />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
<ListBox Name="theControl" Style="{StaticResource myListBoxStyle}" />
来自不同州组的州(选中和鼠标悬停)争夺同一个属性(myBorders的背景)会发生什么。您必须添加另一个元素(可能是矩形),并在其中一种状态下更改该元素的背景
通常,您不应该从不同状态组中的状态操作同一元素的相同属性。Visual state manager不知道如何处理这种情况,因为它不知道哪个状态应该优先。谢谢。我应该想到这一点。对于遇到类似问题的其他人,我在第一个边框内添加了另一个边框,该边框具有相同的形状,并从透明设置为选定时的颜色。现在工作得很好。