WPF - ListBox Background Color - CodeBehind
I am trying to set the background color for a list box in code. I can get it to work with the list item, but not the list itself.
Here's the code that works (with a ListBoxItem):
private void SetBackgroundGradient()
{
var styleListBox = new Style(typeof(ListBoxItem));
var myBrush = new LinearGradientBrush();
myBrush.GradientStops.Add(new GradientStop(Color.FromArgb(255, 0, 0, 0), 0.0));
myBrush.GradientStops.Add(new GradientStop(Color.FromArgb(255, 255, 255, 255), 1.0));
styleListBox.Setters.Add(new Setter
{
Property = BackgroundProperty,
Value = myBrush
});
lstTopics.ItemContainerStyle = styleListBox;
}
Now if I change the code to try and work with the ListBox itself, all I get is a white background. Here's the code for that:
private void SetBackgroundGradient()
{
var styleListBox = new Style(typeof(ListBox));
var myBrush = new LinearGradientBrush();
myBrush.GradientStops.Add(new GradientStop(Color.FromArgb(255, 0, 0, 0), 0.0));
myBrush.GradientStops.Add(new GradientStop(Color.FromArgb(255, 255, 255, 255), 1.0));
styleListBox.Setters.Add(new Setter
{
Property = BackgroundProperty,
Value = myBrush
});
lstTopics.Style = styleListBox;
}
Any idea what I might be doing wrong?
If you need to clarify what I am asking for, please let me know.
Thanks in advance.
a source to share
I solved my problem. This was due to my own mistake.
In the ListBox attributes, I had the following:
Background = "{x: Null}"
I have no idea how this happened. Perhaps something is set by default.
Well, that's settled. The code above is executed. You can set the background of the list as a gradient by code if you don't have a Background = null value :)
thanks
a source to share