HierarchicalDataTemplate練習

  • 1028
  • 0
  • 2014-06-23

HierarchicalDataTemplate 的練習,做出檔案總管左邊 TreeView 的效果。

我試著用 HierarchicalDataTemplate 做出檔案總管左邊TreeView的效果,記錄一下備忘。

Xaml :

<Window x:Class="HierarichicalDataTemplateTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:HierarichicalDataTemplateTest"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <HierarchicalDataTemplate 
            x:Key="MyitemTemplate"
            ItemsSource="{Binding}">
            <TextBlock Text="{Binding Name}"/>
        </HierarchicalDataTemplate>
    </Window.Resources>
    <Window.DataContext>
        <local:MyDataColl/>
    </Window.DataContext>
    <Grid>
        <TreeView ItemsSource="{Binding}" 
                  ItemTemplate="{StaticResource MyitemTemplate}" 
                  BorderBrush="Blue">
        </TreeView>        
    </Grid>
</Window>

C# code (MainWindow) :

using System.Windows;
using System.IO;

namespace HierarichicalDataTemplateTest
{
    /// 
    /// MainWindow.xaml 的互動邏輯
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();            
        }
    }
}

 

C# Code (MyDataColl) :

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace HierarichicalDataTemplateTest
{
    
    class MyDataColl : List
    {
        public MyDataColl()
        {
            FullName = @"Z:\";
            Name = GetName(FullName);
            GenerateItems(FullName);
        }
        public MyDataColl(string spath)
        {
            FullName = spath;
            Name = GetName(spath);
            if (Directory.Exists(spath))
            {                
                GenerateItems(spath);
            }            
        }
        void GenerateItems(string spath)
        {
            string[] datas = Directory.GetFileSystemEntries(FullName);
            foreach (string df in datas)
            {
                this.Add(new MyDataColl(df));
            }
        }
        string GetName(string spath)
        {
            //若spath是目錄,也要用Path.GetFileName才能取得目錄名,
            //用Path.GetDirectoryName會取到上一層的目錄名
            string name = Path.GetFileName(spath);
            string root = Directory.GetDirectoryRoot(spath);
            if (string.IsNullOrEmpty(name))
                name = root;

            return name;
        }
        public string Name { get; set; }
        public string FullName { get; set; }
        
    }
}

 

圖: