两种方法创建WPF目录树TreeView和GridView数据绑定

 效果

定义数据结构

public class DirectoryInformation
{
    public DirectoryInfo Info { get; set; }

    public IEnumerable Files
    {
        get
        {
            return Info.GetFiles();
        }
    }

    public IEnumerable Directories
    {
        get
        {
            try
            {
                return from di in Info.GetDirectories() select new DirectoryInformation { Info = di };
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}

方法一,在CS代码中自动生成列,并绑定数据

UI界面代码


   
       
       
       
   

   
       
           
               
                   
               

           

       

   

   
   
       
           
           

       

   

CS代码

public MainWindow()
{
    InitializeComponent();
    LoadFilePanel();
}

private void LoadFilePanel()
{
    LoadDirectoryTree();
    LoadDetailView();
}

private void LoadDirectoryTree()
{
    var drives = new ObservableCollection();

    foreach (var drive in DriveInfo.GetDrives())
    {
        drives.Add(
            new DirectoryInformation
            {
                Info = new DirectoryInfo(drive.RootDirectory.FullName)
            }
        );
    }

    leftDirectoryTree.ItemsSource = drives;
}

private void LoadDetailView()
{
    List requiredProperties = new List
    {
        "Name", "Length", "IsReadOnly", "LastWriteTime"
    };
 
    foreach (string name in requiredProperties)
    {
        GridViewColumn colmun = new GridViewColumn { Header = name };
        Binding binding = new Binding(name);
        colmun.DisplayMemberBinding = binding;
        leftDetailView.Columns.Add(colmun);
    }
}

方法二,修改以上代码,在XAML中设置固定列,并绑定数据


   
       
           
           
           
       

   

CS代码,只需要加载目录树即可

private void LoadFilePanel()
{
    LoadDirectoryTree();

 

另外,设置DataTemplate可以自定义每个单元格的显示效果,具体可以再网上搜索一下。

List

<DataTemplate>

<StackPanel Orientation="Horizontal" x:Name="richNameContainer">

<Image Source="{Binding FullName, Converter={StaticResource pathToSmallIcon}}"/>

<Grid>

<TextBlock x:Name="fileName" Margin="3,3" Text="{Binding Name}"/>

Grid>

StackPanel>

DataTemplate>

Tile

<DataTemplate x:Key="tileViewTemplate">

<StackPanel Height="110" Width="80">

<Image Source="{Binding FullName, Converter={StaticResource pathToLargeIcon}}"/>

<Grid HorizontalAlignment="Center">

<TextBlock x:Name="fileName" Text="{Binding Name}" TextWrapping="Wrap"/>

Grid>

StackPanel>

DataTemplate>

你可能感兴趣的:(软件开发,WPF,wpf,binding,listview,header,exception,数据结构)