2011-08-14 149 views
6

我无法设置列表框上选定项目的背景颜色。在这个例子中,我不需要交替的颜色。我把他们作为一个测试,他们的工作。触发器IsSelected正在触发,因为前进到粗体且前景变为红色。将高亮颜色刷设置为SteelBlue不会达到预期的效果,因为当ListBox失去焦点时它会消失。当ListBox失去焦点并且是我想要的时候,红色和粗体会保持不变。我想要背景颜色采取和举行选定的项目。现在所选项目的背景为白色,并在列表框失去焦点时保留。感谢您的帮助,我会测试任何建议的修复。设置列表框中选定项目的背景颜色

<ListBox Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="1" Name="WFEnum" Visibility="Visible" BorderThickness="2" Margin="1" Padding="2,2,7,2" 
      ItemsSource="{Binding Path=SearchItem.SrchWorkFlows}" HorizontalAlignment="Left" 
      PresentationTraceSources.TraceLevel="High" AlternationCount="2" > 
     <ListBox.ItemContainerStyle> 
      <Style TargetType="ListBoxItem"> 
       <Setter Property="VerticalContentAlignment" Value="Center" /> 
       <Style.Triggers> 
        <Trigger Property="ItemsControl.AlternationIndex" Value="0"> 
         <Setter Property="Background" Value="LightGreen"></Setter> 
        </Trigger> 
        <Trigger Property="ItemsControl.AlternationIndex" Value="1"> 
         <Setter Property="Background" Value="LightPink"></Setter> 
        </Trigger> 
        <Trigger Property="IsSelected" Value="True" > 
         <Setter Property="FontWeight" Value="Bold" /> 
         <Setter Property="Background" Value="SteelBlue" /> 
         <Setter Property="Foreground" Value="Red" /> 
        </Trigger> 
       </Style.Triggers> 
       <Style.Resources> 
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/> 
       </Style.Resources> 
      </Style> 
     </ListBox.ItemContainerStyle> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <TextBlock Text="{Binding Path=Name, Mode=OneWay}" Background="Transparent" /> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 

回答

14

您指定与SystemColors.HighlightBrushKey一个ListBox的背景的SelectedItem(专注)和SystemColors.ControlBrushKey(不专注)

<Style.Resources> 
    <!-- Background of selected item when focussed --> 
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" 
        Color="Green"/> 
    <!-- Background of selected item when not focussed --> 
    <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" 
        Color="LightGreen" /> 
</Style.Resources> 
+9

值得一提的是,截至2015年1月,这对标准主题的System.Windows.Controls.ListBox的选择高亮颜色没有影响。触发器适用于前台,但不适用于后台。你必须重新设定ListBoxItem。 –

10
<ListBox.Resources> 
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}">SteelBlue</SolidColorBrush> 
</ListBox.Resources> 

如果你想这个应用失焦,以及你需要重写附加键:

<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}">SteelBlue</SolidColorBrush> 
+0

我不得不接受另一个语法作为一个小清洁,但我给你+1谢谢 – Paparazzi

+2

@BalamBalam:“干净”是有争议的,我的答案是七分钟快,哦,好吧,谢谢不管怎么说... –

+1

@ H.B。对不起,实际上并没有注意到你在我之前回答了几乎相同的事情。无论如何,这里是+1 –

相关问题