WPF SelectedItem color disappears when the list lo

2019-05-02 11:58发布

问题:

I have a WPF Window which basically has a ListBox which displays a list of items.

I then have a ListView basically displaying the details of the SelectedItem in the ListBox.

The thing is, when the focus is not on the ListBox anymore, the highlighting color disappears and I cannot see which master item was selected anymore.

Do you know how I can solve this? (ie. making sure that the item stays highlighted)

回答1:

The quickest way is to use a style on the ListBoxItem to override the default System colors:

<Style TargetType="ListBoxItem">
   <Style.Resources>
      <!--SelectedItem with focus-->
      <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" 
         Color="LightBlue" Opacity=".4"/>
      <!--SelectedItem without focus-->
      <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" 
         Color="LightBlue" Opacity=".4"/>
   </Style.Resources>
</Style>

This is kind of a shortcut to the slightly more complex (but easier to control) method of defining the ItemTemplate for the list items. There are plenty of examples of that online, so I won't put that here.



回答2:

Check out this MSDN blog post



回答3:

<Style>
   <Style.Triggers>
      <DataTrigger Binding="{Binding RelativeSource=
                       {RelativeSource Mode=FindAncestor,
                        AncestorType={x:Type ListBoxItem}},
                        Path=IsSelected}" 
      Value="True">
         <Setter Property="Panel.Background" Value="Red" />
      </DataTrigger>
   </Style.Triggers>
</Style>


回答4:

This problem can also be solved with data binding. If the ListView/ListBox SelectedItem is bound to a property in a ViewModel that implements INotifyPropertyChanged and the binding mode is "TwoWay", then when the ListView/ListBox gains focus again, the data binding will select automatically the previously selected item.