如何自定义列表框当前选定项目的颜色?
这个问题是我在stackoverflow中遇到的最后一个问题.自动滚动到特定项目的问题已解决,但现在我想将所选项目的背景设置为透明或白色.我该怎么办??
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??
更新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>
选择ExpressionBlend中的列表框:
Select the listbox in ExpressionBlend:
然后在上级菜单中选择对象",然后选择:
Then select "Object" in the superior menu and choose:
这将创建一个新的ListBoxItemStyle,对于新样式,将基于原始样式创建一个新的ListBoxItem模板.在默认模板中,已经存在一些用于根据触发器和视觉状态更改元素视觉的逻辑.元素被选中时的外观由触发器驱动,您可以对其进行修改以满足您的需求.
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.
选择视图触发器.将有一些由"IsSelected"属性驱动的触发器.在该项目被选中,选中和禁用等情况下,您可以在那里更改其外观.
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.
只需从现有的触发器中选择所需的触发器(例如,"IsSelected = True"),然后使用Blend记录修改模板元素的属性.默认情况下,有一些针对目标元素"的属性更改,这意味着模板本身,例如前景".其他则以模板元素为目标,例如Border"Bd".
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".
当然,您可以从头开始创建ListBoxItemStyle,但是如果您只想进行简单的更改,则这种方法会更快.
Of course you can create your ListBoxItemStyle from scratch, but this way is faster if you just want to make simple changes.