我在WPF中设置HighlightBrushKeySelectedItemListbox时遇到了问题。我的意图是根据代码中给定的 bool 值设置项目的颜色。

我尝试了以下步骤:

  • 实现转换器,检查 bool 值并返回正确的颜色。

    例子:
    <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方法仅被调用一次,但是每次选择一个项目并检查 bool 值时,我都需要调用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>
    

  • 提前致谢! :)

    最佳答案

    <Style x:Key="listBoxStyle" TargetType="{x:Type ListBox}">
        <Style.Resources>
             <!-- Background of selected item when focussed -->
             <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Red" />
             <!-- Background of selected item when not focussed -->
             <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Green" />
        </Style.Resources>
    </Style>
    
    <ListBox Style="{StaticResource listBoxStyle}">
    </ListBox>
    

    关于WPF更改ListboxItem选中时突出显示颜色,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11152982/

    10-13 05:18
    查看更多