0

I am trying to create a style for my ListBoxItem, however the style is not being applied.

Can anyone tell me what's wrong?

Code:

XAML:

<ListBox>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel IsItemsHost="True" Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBoxItem Style="{StaticResource MyListStyle}" Content="Test1" Foreground="Gray"/>
    <ListBoxItem Style="{StaticResource MyListStyle}" Content="Test2" Foreground="Gray"/>
</ListBox>

Style:

<Style x:Key="MyListStyle" TargetType="{x:Type ListBoxItem}">
        <Setter Property="Background" Value="Transparent"></Setter>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Foreground" Value="Black" />
            </Trigger>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Foreground" Value="White"/>
            </Trigger>
        </Style.Triggers>
</Style>

enter image description here

1 Answers1

1

Because WPF properties is listed from highest to lowest precedence

So your ListBoxItem.Foreground is local setting, highest than other

 <ListBoxItem Style="{StaticResource MyListStyle}" Content="Test2" Foreground="Gray"/>

You can remove

<ListBoxItem Style="{StaticResource MyListStyle}" Content="Test2"/>

And set Foreground in StaticResource style

<Style x:Key="MyListStyle" TargetType="{x:Type ListBoxItem}">
        <Setter Property="Background" Value="Transparent"></Setter>
        <Setter Property="Foreground" Value="Gray"></Setter>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Foreground" Value="Black" />
            </Trigger>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Foreground" Value="White"/>
            </Trigger>
        </Style.Triggers>
    </Style>

You can find precedence list in wpf.2000things

And MSDN Dependency Property Setting Precedence List

Allen Hu
  • 141
  • 6