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

Eri*_*ark 4 c# wpf background stackpanel

我正试图在c#中设置TreeViewItem- >的属性,StackPanel就像这个问题一样.它似乎很有意义,直到我到达我尝试编辑Background我的部分Border.它们中BordersBackground物体,但对于我的生命,我无法设置颜色或任何东西.它似乎是不一致的,因为我可以通过简单地说,添加Content到a .LabelContent = "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"
             }
         }
     }
}; 
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

Ana*_*aev 9

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

MyLabel.Background = Brushes.Aquamarine;
Run Code Online (Sandbox Code Playgroud)

或这个:

SolidColorBrush myBrush = new SolidColorBrush(Colors.Red);
MyLabel.Background = myBrush;
Run Code Online (Sandbox Code Playgroud)

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

BrushConverter MyBrush = new BrushConverter();

MyLabel.Background = (Brush)MyBrush.ConvertFrom("#ABABAB");
Run Code Online (Sandbox Code Playgroud)

将属性设置为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;
Run Code Online (Sandbox Code Playgroud)

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

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);
}
Run Code Online (Sandbox Code Playgroud)