1

我正在尝试为代码中的列表框设置背景颜色。我可以让它与列表框项目一起使用,但不是列表框本身。

这是有效的代码(使用 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;
    }

现在,如果我更改代码以尝试使用 ListBox 本身,我得到的只是白色背景。这是代码:

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;
    }

知道我可能做错了什么吗?

如果您需要对我的要求进行任何澄清,请告诉我。

提前致谢。

4

1 回答 1

2

我解决了我自己的问题。这是由于我自己的错误。

我在 ListBox 属性中有以下内容:

背景="{x:Null}"

我不知道那是怎么到那里的。可能以某种方式默认设置。

嗯,解决了。上面的代码有效。您可以通过代码将列表框的背景设置为渐变,只要您没有设置 Background = null :)

谢谢

于 2009-05-10T03:16:01.397 回答