Search code examples
c#wpfbackgroundstackpanel

How to use code-behind to create StackPanel -> Border -> Background


I'm trying to set properties of a TreeViewItem -> StackPanel in c# like this question. It seems to make a lot of sense until I get to the part where I try to edit the Background in my Border. Borders have Background objects in them, but for the life of me I can't set a color or anything. It seems to be inconsistent because I can add Content to a Label by simply saying, Content = "Title".

Anyway, this is my code:

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 - I have the same problem when trying to add a BorderBrush

Thank you!


Solution

  • Background property accepts an Brush. Therefore, the code can set the color as follows:

    MyLabel.Background = Brushes.Aquamarine;
    

    Or this:

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

    To set any color, you can use BrushConverter:

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

    Setting the property to the LinearGradientBrush in code:

    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;
    

    For you it would look like this:

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