我想使用数据绑定(bind)更改选定列表框项目的背景/突出显示颜色。这是我所尝试过的,但它不起作用。我不确定如何让资源部分具有“当前项目”上下文。
颜色是每个显示项目的属性(并且每个项目都有不同的值)。
<ListBox x:Name="Categorie" ItemsSource="{Binding Categories}" IsSynchronizedWithCurrentItem="True">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="{Binding /Color}" />
</Style.Resources>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="{Binding /Color}" />
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" HorizontalAlignment="Center"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
最佳答案
您可以使用 Trigger
实现这一目标:
<Style TargetType="ListBoxItem">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="{Binding Color}" />
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
请注意,要使此绑定(bind)起作用,您必须有一个名为 Color
的属性。在设置为 ListBox.ItemsSource
的数据项对象上.
更新>>>
好吧,那是我的错...我忘了SolidColorBrush
不是FrameworkElement
是 Freezable
,因此它们不能用于 Binding
...您有几个选择:
将您的颜色创建为 StaticResource
对象:
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="{StaticResource Color}" />
</Trigger>
或者您可以绑定(bind) Background
属性(property)Color
使用 Converter
的对象某种类型:
<Style TargetType="ListBoxItem" Background="{Binding Color, Converter={StaticResource
SomeColourConverter}}" />
关于wpf - 根据数据更改所选列表框项目的背景/突出显示颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18461873/