以编程方式将节点图像的背景设置为颜色

本文关键字:背景 设置 颜色 图像 编程 方式 节点 | 更新日期: 2023-09-27 18:33:35

下面的代码生成一个树视图节点,其中包含一个图标(来自.PNG文件Piconfolder''PiconName),后跟一个文本字符串Pheader。我想只为图标添加背景(与透明图标一起使用)

public static TreeViewItem CreateTreeViewItem(
         string Pheader,
         string PiconFolder,
         string PiconName)
    {
        string iconFolder = PiconFolder;
        string iconName = PiconName;
        string header = Pheader;
        TreeViewItem child = new TreeViewItem();
        StackPanel pan = new StackPanel();
        pan.Orientation = Orientation.Horizontal;
        string fPath = System.IO.Path.Combine(iconFolder, iconName);
        Image image = new Image();
        image.Height = 16;
        image.Width = 16;
        image.Source = new BitmapImage(new Uri(fPath,  uriKind.RelativeOrAbsolute));
        pan.Children.Add(image);                             
        pan.Children.Add(new TextBlock(new Run("  " + header)));
        child.Header = pan;  
   }

以编程方式将节点图像的背景设置为颜色

替换

pan.Children.Add(image);

var iconPanel = new Grid(); // or other panel
iconPanel.Background = Brushes.Blue;
iconPanel.Children.Add(image);
pan.Children.Add(iconPanel);