简体   繁体   中英

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.

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:

在此处输入图片说明

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

在此处输入图片说明

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.

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM