WPF 中TreeView 的动态加载和自定义布局(图片+文字)

        <TreeView Name="system_tree" Grid.Column="0" Grid.Row="0"  Background="#FF116EAA" Padding="0"   ItemContainerStyle="{StaticResource myLBStyle}" >
                <!--<TreeViewItem>
            </TreeViewItem>-->
            </TreeView>

1 先定义一个树控件在xmal文件中,在cs文件中进行动态的加载树的内容


2 为每一个树节点进行布局的设置,你可以设计成任何你想要的布局,返回你想要的stackpanel 即可

  private StackPanel createTreeViewItem(string value,BitmapImage btmapImg)
        {
            StackPanel panel = new StackPanel();
            panel.Height = 45;
            panel.Width = 100;
            panel.Orientation = Orientation.Horizontal;

            if (btmapImg != null)
            {
                Image img = new Image();
                img.Source = btmapImg;
                panel.Children.Add(img);
            }

            Label lb = new Label();
            lb.FontSize = 17;
            lb.Foreground = new SolidColorBrush(Color.FromRgb(255,59,59));
            lb.Content = value;
            lb.VerticalAlignment = VerticalAlignment.Center;
            lb.HorizontalAlignment = HorizontalAlignment.Center;
            lb.Foreground = new SolidColorBrush(Colors.White);
            panel.Children.Add(lb);
            return panel;
        }

3 按照你的需求,可以添加任意的层级,每一个层级都是一个我们设计的stackpanel ,这里我是设计了一个图片+一个文字标签的布局

  private StackPanel createTreeViewItem(string value,BitmapImage btmapImg)
        {
            StackPanel panel = new StackPanel();
            panel.Height = 45;
            panel.Width = 100;
            panel.Orientation = Orientation.Horizontal;

            if (btmapImg != null)
            {
                Image img = new Image();
                img.Source = btmapImg;
                panel.Children.Add(img);
            }

            Label lb = new Label();
            lb.FontSize = 17;
            lb.Foreground = new SolidColorBrush(Color.FromRgb(255,59,59));
            lb.Content = value;
            lb.VerticalAlignment = VerticalAlignment.Center;
            lb.HorizontalAlignment = HorizontalAlignment.Center;
            lb.Foreground = new SolidColorBrush(Colors.White);
            panel.Children.Add(lb);
            return panel;
        }


4 上图

WPF 中TreeView 的动态加载和自定义布局(图片+文字)_第1张图片


你可能感兴趣的:(C#,树,WPF)