4

我正在尝试像这个问题一样在 c#中设置TreeViewItem->的属性。在我尝试在我的. 里面有物体,但对于我的生活,我无法设置颜色或任何东西。这似乎是不一致的,因为我可以通过简单地说,添加到 a中。StackPanelBackgroundBorderBordersBackgroundContentLabelContent = "Title"

无论如何,这是我的代码:

public static TreeViewItem childNode = new TreeViewItem() //Child Node 
{
     Header = new StackPanel
     {
         Orientation = Orientation.Horizontal,
         Children =
         {
             new Border {
                 Width = 12,
                 Height = 14,
                 Background = ? //How do I set the background?
             },
             new Label {
                 Content = "Child1"
             }
         }
     }
}; 

PS - 我在尝试添加时遇到同样的问题BorderBrush

谢谢!

4

1 回答 1

9

Background属性接受Brush. 因此,代码可以设置颜色如下:

MyLabel.Background = Brushes.Aquamarine;

或这个:

SolidColorBrush myBrush = new SolidColorBrush(Colors.Red);
MyLabel.Background = myBrush;

要设置任何颜色,您可以使用BrushConverter

BrushConverter MyBrush = new BrushConverter();

MyLabel.Background = (Brush)MyBrush.ConvertFrom("#ABABAB");

将属性设置为LinearGradientBrushin 代码:

LinearGradientBrush myBrush = new LinearGradientBrush();

myBrush.GradientStops.Add(new GradientStop(Colors.Yellow, 0.0));
myBrush.GradientStops.Add(new GradientStop(Colors.Green, 0.5));
myBrush.GradientStops.Add(new GradientStop(Colors.Red, 1.0));

MyLabel.Background = myBrush;

对你来说,它看起来像这样:

private void Window_ContentRendered(object sender, EventArgs e)
{
    TreeViewItem childNode = new TreeViewItem()
    {
        Header = new StackPanel
        {
            Orientation = Orientation.Horizontal,

             Children =
             {
                 new Border
                 {
                     Width = 12,
                     Height = 14,
                     Background = Brushes.Yellow, // Set background here
                 },

                 new Label 
                 {
                     Content = "Child1", 
                     Background = Brushes.Pink, // Set background here
                 }
             }
        }
    };

    MyTreeView.Items.Add(childNode);
}
于 2013-08-02T15:38:11.170 回答