c# - How to change a listbox unselected item colour from code behind



I have to create listBox via code behind. After that I have to change the colour that the selected item has when the listbox is not selected. I have found that solution but am not able to render it via code behind.

enter image description here

Thank you

2 Answers: 

Very easy if it's ok for you overriding the windows colour on the listbox

listBox1.Resources[SystemColors.InactiveSelectionHighlightBrushKey] = Brushes.Blue;

I picked your rgb colour so to be precise it's:

listBox1.Resources[SystemColors.InactiveSelectionHighlightBrushKey] = new SolidColorBrush(Color.FromArgb(255, (byte)51, (byte)153, (byte)255));

As you've already seen the answer as in the link, you need to apply a style. Now You need help applying that style (defined in XAML) via code behind? If yes then apply the below code:

Style style = this.FindResource("YourStyleName") as Style;
myListBox.Style = style;

The above code works if your style is defined in the same Window's XAML. If it's somewhere else, follow the below code:

Style style = Application.Current.FindResource("YourStyleName") as Style;
myListBox.Style = style;

That being said, I would not recommend adding a listbox via C# as it can be tough to handle UI via C#. I would recommend defining listbox in XAML and using databinding, INotifyPropertyChanged to reduce your code complexity.

I hope I've answered your question. let me know if there is anything else in the comments section.

Also, please note: in the question the link you've mentioned. exactly like that the style will go in the XAML