【问题标题】:How to use code-behind to create StackPanel -> Border -> Background如何使用代码隐藏创建 StackPanel -> 边框 -> 背景
【发布时间】:2013-08-02 15:31:10
【问题描述】:

我正在尝试在 c# 中设置 TreeViewItem -> StackPanel 的属性,例如 this question。在我尝试在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 时遇到同样的问题

谢谢!

【问题讨论】:

  • 您有什么理由选择这种方法而不是视图/视图模型类型方法?
  • 我还是刚开始使用 MVVM,发现有时不使用它更容易。
  • This MSDN article 可能会比您想要的更详细,但它可能会大大简化您的 WPF 开发。

标签: c# wpf background stackpanel


【解决方案1】:

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

【讨论】:

  • 这一切都非常有帮助。我注意到每当您设置Background 时,您就有object.Backgroun = myBrush;。正如你所看到的,我的边界并没有真正的名字。无论如何要在Border 中添加它,就像我的问题一样?
  • @Ericafterdark 您需要将其保存到变量中。在 XAML 中应用 x:Name 实际上与将控件保存到私有类变量没有什么不同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-19
  • 1970-01-01
  • 1970-01-01
  • 2011-09-12
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多