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,
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:"
gLBxEpidemicSequence.SelectionBackground = Brushes.Blue;
"This will change the background color of the selected item to blue."
---
When I use SelectionBackground
gLBxEpidemicSequence.SelectionBackground = Brushes.Blue;
the error message is:
'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.
Tuhin PaulPosted Mar 14, 2024, 7:47 PM
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:Tuhin PaulPosted Mar 14, 2024, 7:45 PM
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.Naimish MakwanaPosted Mar 14, 2024, 12:16 PM
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