Kimbo
Kimbo

Reputation: 1388

How to customize the color of the currently selected item of a listbox?

This question results out of my last question here in stackoverflow. The problem to scroll automatically to a specific item is solved, but now i want to set the selected item background to transparent or white. How can i do this??

Update 1

<ListBox ItemsSource="{Binding SomeData}"
         SelectedIndex="{Binding SomeIndex}">
   <ListBox.ItemsPanel>
      <ItemsPanelTemplate>
         <WrapPanel Orientation="Vertical" />
      </ItemsPanelTemplate>
   </ListBox.ItemsPanel>
   <ListBox.ItemTemplate>
      <DataTemplate>
         <SomeChart DataContext="{Binding }" />
      </DataTemplate>
   </ListBox.ItemTemplate>
 </ListBox>

And for this example i need a way to customize the selecteditem color.

Upvotes: 1

Views: 467

Answers (1)

Arthur Nunes
Arthur Nunes

Reputation: 7048

Starting with a simple listbox in a window:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow"
    Width="525"
    Height="350">
<Window.DataContext>
    <local:ViewModel />
</Window.DataContext>
<Grid Name="LayoutRoot">
    <ListBox ItemsSource="{Binding Elements}"/>
</Grid>

Select the listbox in ExpressionBlend:

enter image description here

Then select "Object" in the superior menu and choose:

enter image description here

This will create a new ListBoxItemStyle and, for the new style, a new ListBoxItem Template, based on the original. In the default template there is already some logic for changing the visual of the element based in triggers and visualstates. The visual of the element when it is selected is driven by a trigger, which you can modify to acomplish your needs.

Select the view triggers. There will some triggers driven by the "IsSelected" property. There you can change the appearence of the item when it is selected, selected and disabled, etc.

enter image description here

Just select the trigger you want from the existing ones (for example, the "IsSelected = True") and modify the properties of elements of the template with Blend recording. By default, there is some properties changes targeting a "target-element", meaning the template itself, like "Foreground". Others target elements of the template, like the Border "Bd".

Of course you can create your ListBoxItemStyle from scratch, but this way is faster if you just want to make simple changes.

Upvotes: 2

Related Questions