C# wpf --- This is a "continuation" of c-sharpcorner.com/forums/how-do-change-the-background-color-on-one-listbox-item-continued.
When I highlight one ListBox item,
C#
gLBxEpidemicSequence.SelectedIndex = iIndex;the background is Gray. How do I change the background color?
---
The response, by Abhishek Yadav, was "you can do the following:"
C#
gLBxEpidemicSequence.SelectionBackground = Brushes.Blue;"This will change the background color of the selected item to blue."
---
When I use SelectionBackground
C#
gLBxEpidemicSequence.SelectionBackground = Brushes.Blue;the error message is:
C#
'ListBox' does not contain a definition for 'SelectionBackground' and no
accessible extension method 'SelectionBackground' accepting a first argument
of type 'ListBox' could be found (are you missing a using directive or an
assembly reference?)Please advise.

Naimish MakwanaRank #324 · 7.7K reputationPosted Mar 14, 2024, 8:16 AM EDT
In WPF, the
ListBoxcontrol does not have aSelectionBackgroundproperty. Instead, you can change the background color of a selected item by modifying theListBox’s item container style. Here’s an example:In this example, when an item is selected (
IsSelectedisTrue), theBackgroundproperty of theListBoxItemis set toBlue. This will change the background color of the selected item to blue.You can replace
Bluewith any color you prefer. If you want to do this in C# code behind, you will need to create a newStyleobject, add aTriggerto it, and then assign it to theItemContainerStyleproperty of yourListBox. However, it’s generally easier and more maintainable to do this kind of styling in XAML.Thanks
Tuhin PaulRank #7 · 71.9K reputationPosted Mar 14, 2024, 3:45 PM EDT
The error message you're encountering is because
ListBoxin WPF doesn't have a built-in property calledSelectionBackground. While the previous response suggested usingSelectionBackground, it's not the correct approach.Tuhin PaulRank #7 · 71.9K reputationPosted Mar 14, 2024, 3:47 PM EDT
Actually change the background color of the selected item in your WPF ListBox.
Method 1: Using ItemContainerStyle
This method involves modifying the ListBox's item container style. Styles define the visual appearance of controls. Here's how to do it:
Set the ItemContainerStyle:
In your XAML code, define an
ItemContainerStylefor the ListBox:Inside the
Styledefinition, use aTriggerthat fires when an item is selected (IsSelectedproperty isTrue) and set theBackgroundproperty of theListBoxItem: