I want to make a menu from a ListBox How can I change the text and image color when an item is selected?
Example:
I got it like this:
Code XAML:
<ListView Background="Transparent"
BorderBrush="Transparent"
HorizontalAlignment="Left"
Margin="0 0 0 0">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListViewItem">
<Border Name="_Border" Margin="3 0 3 0" Padding="5 5 5 5"
CornerRadius="3"
SnapsToDevicePixels="true"
Background="Transparent">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="_Border" Property="Background" Value="#36A3F6"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListViewItem IsSelected="True">
<StackPanel Orientation="Horizontal">
<Image Source="Images/home.png" Width="15" Height="15" Margin="5 0 5 0"/>
<TextBlock Text="item1"/>
</StackPanel>
</ListViewItem>
<ListViewItem>
<StackPanel Orientation="Horizontal">
<Image Source="Images/home.png" Width="15" Height="15" Margin="5 0 5 0"/>
<TextBlock Text="item2"/>
</StackPanel>
</ListViewItem>
<ListViewItem>
<StackPanel Orientation="Horizontal">
<Image Source="Images/home.png" Width="15" Height="15" Margin="5 0 5 0"/>
<TextBlock Text="item3"/>
</StackPanel>
</ListViewItem>
</ListView>
CodePudding user response:
To change the Text color you could simply put another Setter into your "IsSelected"-Trigger like:
<Setter Property="Foreground" Value="White"/>
Changing the color of the .png-Image wont be that simple though. You should consider converting your Icons (like the home.png) into Paths, so you can transform them easier and change their color ("Fill"-Property)
If you want to go further with your project, also consider putting your styles into seperate ResourceDictionaries to clean up your code