How to use code to create StackPanel & # 8594; Border & # 8594; Background

I am trying to set TreeViewItem StackPanel in C #, for example this question . This seems to make a lot of sense until I get to the part where I'm trying to edit Background in my Border . Borders have Background objects in them, but for the life of me I cannot set the color or anything else. This seems inconsistent because I can add Content to the Label simply by 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 BorderBrush

Thanks!

+4
source share
1 answer

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

 MyLabel.Background = Brushes.Aquamarine; 

Or that:

 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 a property in 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; 

It will look like this for you:

 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); } 
+9
source

Source: https://habr.com/ru/post/1494983/


All Articles