如何使用代码隐藏创建StackPanel – >边框 – >背景
我正在尝试在c#中设置TreeViewItem
– > StackPanel
属性,就像这个问题一样 。 在我到达我尝试编辑Border
Background
的部分之前,它似乎很有意义。 Borders
有Background
对象,但对于我的生活,我无法设置颜色或任何东西。 它似乎不一致,因为我可以通过简单地说Content = "Title"
将Content
添加到Label
。
无论如何,这是我的代码:
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
时遇到同样的问题
谢谢!
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); }