【发布时间】:2012-06-24 13:30:16
【问题描述】:
我在 WPF 中设置 SelectedItem 的 HighlightBrushKey 和 Listbox 时遇到问题。我的意图是根据给定的布尔值设置项目的颜色,位于代码中。
我尝试了以下步骤:
-
实现一个转换器,检查布尔值并返回正确的颜色。
例子:
<ribbon:RibbonWindow.Resources> <l:WindowControl x:Key="ListBoxItemBackgroundConverter" /> <Style x:Key="listBoxStyle" TargetType="{x:Type ListBoxItem}"> <Style.Resources> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="{Binding Source={x:Static SystemColors.HighlightBrushKey}, Converter={StaticResource ListBoxItemBackgroundConverter}}"/> <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="{Binding Source={x:Static SystemColors.ControlBrushKey}, Converter={StaticResource ListBoxItemBackgroundConverter}}"/> </Style.Resources> </Style> </ribbon:RibbonWindow.Resources>这里的问题是 Convert 方法只被调用了一次,但是我每次选择一个项目并检查布尔值时都需要调用 Converter。类似于触发器,但带有“
HighlightBrushKey”。转换器:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if(currentField == null) return Brushes.Yellow; if (currentField.Save) return Brushes.LightGreen; else return Brushes.Yellow; } -
我的下一个想法是将“
HighlightBrushKey”设置为“Transparent”并在代码中手动更改item.Background。这里的问题是我的物品变成了白色并且看不到背景颜色例子:
<ListBox.Resources> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" /> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black" /> <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" /> </ListBox.Resources>
提前致谢! :)
【问题讨论】:
-
第一个问题很好,安迪,用精确的例子很好地构建了你想要强调的内容! +1
-
@Andy 您的转换器中的 currentField1 是什么?你是如何在转换器中得到这个的?您可以尝试以提供的不可见样式绑定到
currentField(即YourViewModelProperty)吗? -
currentField 是一个对象。类名是 Field 并且有一个名为“Save”的布尔属性。如何在 XAML 中绑定它?
-
听起来你需要一个多值转换器来检查 IsSelected 和你的布尔值
标签: wpf background-color listboxitem