1. 程式人生 > 其它 >WPF中樹狀圖展示

WPF中樹狀圖展示

static List<Mulu> GetMuluList(string path)//獲取一級目錄並記錄到Mulu物件中返回一個mulu型別的list反省集合
{

if (Directory.Exists(path))
{
List<Mulu> ltml = new List<Mulu>();
string[] arrdir = Directory.GetDirectories(path);
for (int i = 0; i < arrdir.Length; i++)
{
Mulu newml = new Mulu() { title = System.IO.Path.GetFileName(arrdir[i]), path = arrdir[i] };
ltml.Add(newml);
SetMuluChildren(newml);
}
return ltml; } else { return null; } } static void SetMuluChildren(Mulu ml) //遞迴設定每個mulu物件path目錄下的子資料夾記錄到children集合中 { string[] arrdir = Directory.GetDirectories(ml.path); ml.numberoffile = Directory.GetFiles(ml.path, "*", SearchOption.AllDirectories).Length; ml.title += " (" + ml.numberoffile + ")";
for (int i = 0; i < arrdir.Length; i++) { Mulu newml = new Mulu() { title = System.IO.Path.GetFileName(arrdir[i]), path = arrdir[i] }; ml.Children.Add(newml); SetMuluChildren(newml); } } public class Mulu { public string title //記錄顯示的標題 { get; set; }
public string path //記錄完整的目錄 { get; set; } public int numberoffile //記錄目錄下所有的檔案數量 包含子目錄 { get; set; } public List<Mulu> Children //記錄子目錄 { get; set; } public Mulu() { Children = new List<Mulu>(); } }

WPF介面中TreeView

<TreeView Name="tv" Grid.Column="0" Margin="0,0,0,-0.333" TreeView.SelectedItemChanged = "tvSelect" >
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Children}">
<StackPanel Orientation="Horizontal">
<Image VerticalAlignment="Center" Source="/WPF_FTP;component/Images/Dir.ico" Width="16" Height="16" Margin="2,2,2,2"></Image>
<TextBlock VerticalAlignment="Center" Text="{Binding title}"></TextBlock>
<StackPanel.ToolTip>
<TextBlock Text="{Binding numberoffile}" TextWrapping="Wrap"></TextBlock>
</StackPanel.ToolTip>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>