mans
mans

Reputation: 18168

style of selected item in lisbox

I have a list box which is bound to a list of strings.

 <ListBox Grid.Row="1"
                 Height="130"
                 Background="Black" BorderThickness="0"
                 ItemsSource="{Binding Images}"
                 ItemTemplate="{StaticResource PanoItemTemplate}"
                 SelectedItem="{Binding SelectedImage}">

            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel Orientation="Horizontal"
                               Height="110"/>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
</ListBox>

and in VM I have:

public ObservableCollection<string> Images
{
  get { return _images; }
}

public string SelectedImage
{
  get { return _selectedImage; }
  set
  {
    _selectedImage = value;
    OnPropertyChanged("SelectedImage");
  }
}

When I populate Image list and select one of them in listbox by clicking on it, I can get it in SelectedImage and the system works well.

When I click on an item on list box, it shows as selected I ListBox (Blue colour on white background).

If I set the SelectedImage in code to an item which is in image list, that item is selected on list, but the colour is different (it is white on white background).

How can I change the style of selectedImage when I select them via code to be the same as when user select them?

Upvotes: 1

Views: 78

Answers (1)

sa_ddam213
sa_ddam213

Reputation: 43596

The ListBox will only highlight blue when it has user focus, otherwise it uses a different brush

When the ListBox is focused it used SystemColors.HighlightTextBrushKey, and when unfocused it uses SystemColors.InactiveSelectionHighlightBrushKey

So you could set the SystemColors.InactiveSelectionHighlightBrushKey to the SystemColors.HighlightColor, this will keep it blue in and out of focus.

Example:

<ListBox >
    <ListBox.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="{x:Static SystemColors.HighlightColor}"/>
    </ListBox.Resources>
</ListBox>

Edit:

For .NET4.0 and below you may have to use SystemColors.ControlBrushKey instead of SystemColors.InactiveSelectionHighlightBrushKey

<ListBox >
    <ListBox.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="{x:Static SystemColors.HighlightColor}"/>
    </ListBox.Resources>
</ListBox>

Upvotes: 2

Related Questions