1

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.

4

1 に答える 1

2

私は自分の問題を解決しました。それは私自身の過ちによるものでした。

ListBoxの属性には次のものがあります。

Background = "{x:Null}"

どうやってそこにたどり着いたのかわかりません。おそらくデフォルトで何らかの形で設定されています。

さて、それは解決されました。上記のコードは機能します。Background = nullが設定されていない限り、コードを介してリストボックスの背景をグラデーションとして設定できます:)

ありがとう

于 2009-05-10T03:16:01.397 に答える