views:

1657

answers:

2

Hello,

I am attempting to set the background color for a list box in code. I can get it to work with the list box item, but not the list box itself.

Here is the code that works (with the 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 to work with the ListBox itself, all I get is a white background. Here is 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 any clarification on what I am asking, please let me know.

Thanks in advance.

+2  A: 

I solved my own issue. It was due to my own error.

I had the following in the ListBox attributes:

Background="{x:Null}"

I have no idea how that got there. Possibly somehow set by default.

Well, it is solved. The code above works. You can set the background of the list box as a gradient via code as long as you don't have the Background = null set :)

Thanks

Jason Heine
A: 

Ok, so I tried it, but it gives me an error on the "new Setter" call: "A new expression requires () or [] after type." Any ideas? Thanks!

Sandman