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

纵饮孤独 提交于 2019-12-11 14:50:03

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/13475216/how-to-customize-the-color-of-the-currently-selected-item-of-a-listbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!