8

我在 WPF 中设置HighlightBrushKeya SelectedItemof a时遇到问题。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>
    

提前致谢!:)

4

2 回答 2

1
<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> 
于 2012-06-26T07:59:43.287 回答
0

如果您希望在选择列表框项或鼠标悬停时禁用突出显示,您可以使用以下代码。

<Style TargetType="ListBoxItem" x:Key="ListBoxItemStyle">
    <Setter Property="IsSelected" Value="{Binding Content.IsSelected, Mode=TwoWay, RelativeSource={RelativeSource Self}}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ListBoxItem">
                <ContentPresenter/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<ListBox ItemContainerStyle="{StaticResource ListBoxItemStyle}"/>
于 2018-12-19T16:07:09.747 回答