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