如何使用代码隐藏创建StackPanel - >边界 - >背景

时间:2013-08-02 15:31:10

标签: c# wpf background stackpanel

我正在尝试设置TreeViewItem - >的属性c {this question中的StackPanel。在我尝试编辑BackgroundBorder的部分之前,它似乎很有意义。 Borders中有Background个对象,但对于我的生活,我无法设置颜色或任何东西。它似乎不一致,因为我可以通过简单地说ContentLabel添加到Content = "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

时遇到同样的问题

谢谢!

1 个答案:

答案 0 :(得分: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");

在代码中将属性设置为LinearGradientBrush

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