天天看點

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 的動态加載和自定義布局(圖檔+文字)