WPF 控件 (二十、TreeView)

一、基本用法

  <TreeView FontSize="16">
      <TreeViewItem Header="动物">
            <TreeViewItem Header="猴子"></TreeViewItem>
            <TreeViewItem Header="老虎"></TreeViewItem>
            <TreeViewItem Header="大象"></TreeViewItem>
        </TreeViewItem>
        <TreeViewItem Header="水果">
            <TreeViewItem Header="苹果"></TreeViewItem>
            <TreeViewItem Header="橘子"></TreeViewItem>
            <TreeViewItem Header="葡萄"></TreeViewItem>
        </TreeViewItem>
        <TreeViewItem Header="蔬菜">
            <TreeViewItem Header="青菜"></TreeViewItem>
            <TreeViewItem Header="白菜"></TreeViewItem>
            <TreeViewItem Header="茄子"></TreeViewItem>
        </TreeViewItem>
    </TreeView>

WPF 控件 (二十、TreeView)_第1张图片

二、绑定

2.1

  <TreeView FontSize="16" Grid.Row="1">
        <TreeViewItem Header="动物" ItemsSource="{Binding animals}"/>
        <TreeViewItem Header="水果" ItemsSource="{Binding fruits}"/>
        <TreeViewItem Header="蔬菜" ItemsSource="{Binding vars}"/>
    </TreeView>
 public List<string> animals { get; set; } = new List<string>() { "老虎", "猴子", "大象" };
 public List<string> fruits { get; set; } = new List<string>() { "苹果", "香蕉", "橘子" };
 public List<string> vars { get; set; } = new List<string>() { "黄瓜", "番茄", "白菜" };
 public TreeViewUserControl()
 {
      InitializeComponent();
      this.DataContext = this;
  }

WPF 控件 (二十、TreeView)_第2张图片

2.2

 <TreeView FontSize="16" Grid.Column="1"  ItemsSource="{Binding items}"/>
 public List<string> animals { get; set; } = new List<string>() { "老虎", "猴子", "大象" };
 public List<string> fruits { get; set; } = new List<string>() { "苹果", "香蕉", "橘子" };
 public List<string> vars { get; set; } = new List<string>() { "黄瓜", "番茄", "白菜" };
 
 public TreeViewUserControl()
      {
          InitializeComponent();

          items.Add(new TreeViewItem() { Header = "动物", ItemsSource = animals });
          items.Add(new TreeViewItem() { Header = "水果", ItemsSource = fruits });
          items.Add(new TreeViewItem() { Header = "蔬菜", ItemsSource = vars });
     
          this.DataContext = this;
      }

WPF 控件 (二十、TreeView)_第3张图片

三、文件目录

     <TreeView FontSize="16" Grid.Column="1"  Grid.Row="1" ItemsSource="{Binding drives}"/>
   public partial class TreeViewUserControl : UserControl
    {
        public List<TreeViewItem> drives { get; set; }
        public TreeViewUserControl()
        {
            InitializeComponent();
            drives = Directory.GetLogicalDrives().Select(d => new TreeViewItem() { Header = d ,Tag = d}).ToList();
            drives.ForEach(d => {
                d.Expanded += D_Expanded;
                d.Items.Add(null);
            } );
            this.DataContext = this;
        }

    

        private void D_Expanded(object sender, RoutedEventArgs e)
        {
            try
            {
                #region Initial Checks
                var item = (TreeViewItem)sender;

                // 获取完整路径
                var fullPath = (String)item.Tag;
                var dirs = Directory.GetDirectories(fullPath, "*", SearchOption.TopDirectoryOnly);
                if (dirs.Length <= 0)
                {
                    return;
                }
                foreach (TreeViewItem i in item.Items) {
                    if (i != null && dirs.Contains(i.Tag)) {
                        return;
                    }
                 }
                dirs.Where(d => (new FileInfo(d).Attributes & FileAttributes.Hidden) != FileAttributes.Hidden).ToList().ForEach(d =>
                {
                    var subItem = new TreeViewItem()
                    {
                        // 将标题设置为文件夹名称
                        Header = GetFileFolderName(d),
                        // 标记为完整路径
                        Tag = d
                    };
                    // 添加虚拟项目,以便我们可以扩展文件夹
                    subItem.Items.Add(null);
                    // 处理扩展
                    subItem.Expanded += D_Expanded;
                    // 将此项目添加到父项
                  
                    item.Items.Add(subItem);
                });
                item.Items.Remove(null);
                #endregion


                #region Get Files
              var Files = Directory.GetFiles(fullPath);
                if (Files.Length <= 0)
                {
                    return;
                }
                Files.ToList().ForEach(f =>
                {
                    // 创建文件
                    var subItem = new TreeViewItem()
                    {
                        // 将标题设置为文件名称
                        Header = GetFileFolderName(f),
                        // 标记为完整路径
                        Tag = f
                    };

                    // 将此项目添加到父项
                    item.Items.Add(subItem);
                });
                #endregion

            }
            catch (Exception ex) {
                MessageBox.Show(ex.ToString());
            }


        }

        private object GetFileFolderName(string path)
        {
            // 如果没有路径,则返回空
            if (string.IsNullOrEmpty(path))
                return string.Empty;

            // 使所有斜杠成反斜杠
            var normalizedPath = path.Replace('/', '\\');

            // 找到最后一个反斜杠就是路径
            var lastIndex = normalizedPath.LastIndexOf('\\');

            // 如果找不到反斜线,则返回路径本身
            if (lastIndex <= 0)
                return path;

            // 最后一个反斜杠后返回名称
            return path.Substring(lastIndex + 1);
        }
    }

在这里插入图片描述
WPF 控件 (二十、TreeView)_第4张图片
WPF 控件 (二十、TreeView)_第5张图片

四、样式

 <TreeView FontSize="16" Grid.Column="2"  Grid.RowSpan="2" ItemsSource="{Binding drives}">
     <TreeView.Resources>
            <Style TargetType="TreeViewItem">
                <Setter Property="HeaderTemplate">
                    <Setter.Value>
                        <DataTemplate >
                            <StackPanel Orientation="Horizontal" Margin="5">
                                <Image Source="../bird1.png" Width="20" Height="20" Stretch="Fill" x:Name="img"/>
                                <TextBlock Text="{Binding}" x:Name="tb" Margin="5,0,0,0"/>
                            </StackPanel>
                        </DataTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </TreeView.Resources>
    </TreeView>

在这里插入图片描述
WPF 控件 (二十、TreeView)_第6张图片
WPF 控件 (二十、TreeView)_第7张图片

你可能感兴趣的:(WPF自定义样式控件,wpf,c#,开发语言)