List directory files in a DataGrid

2020-04-15 15:23发布

问题:

I have searched many topics and can't find an answer on using the WPF DataGrid to list file name contents from a directory. I am able to output the contents in a ListBox but have no idea how to add items to a Column in DataGrid.

This works for a ListBox

string path = "C:";

object[] AllFiles = new DirectoryInfo(path).GetFiles().ToArray();

foreach (object o in AllFiles)
{
    listbox.Items.Add(o.ToString());
}

How can I do the same with a DataGrid? Or atleast place strings from an array into a DataGrid Column?

回答1:

You can create DataGrid with one column:

<DataGrid x:Name="myDataGrid" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn IsReadOnly="True" Binding="{Binding}" Header="Name"/>
    </DataGrid.Columns>
</DataGrid>

and fill it in your code like this:

myDataGrid.ItemsSource = new DirectoryInfo(path).GetFiles();

By setting ItemsSource to FileInfo[] you have option to create other columns bound to other properties for FileInfo class. This DataGrid will work with any IEnumerable assigned to ItemsSource. If it won't be a string already then ToString() will be called



回答2:

You first have to add Columns in your DataGrid (using VS is pretty simple with the designer) and then you can use something like:

for (int i = 0; i < Object.Length; i++)
    dataGrid.Rows[i].Cells[0].Value = Object[i];

In this case i'm using Cells[0], but you can specify any cell on your row to put the values.



回答3:

You should be able to bind your listbox to the DataGrid something like:

<Window x:Class="Bind02.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Bind02" Height="300" Width="300"
>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <ListBox Name="listBox" ItemsSource="{Binding}"/>
        <StackPanel Grid.Column="1">
            <Button Click="OnLoad">_Load</Button>
            <Button Click="OnSave">_Save</Button>
            <Button Click="OnAdd">_Add</Button>
            <Button Click="OnEdit">_Edit</Button>
            <Button Click="OnDelete">_Delete</Button>
            <Button Click="OnExit">E_xit</Button>
        </StackPanel>
    </Grid>
</Window>


回答4:

Instead of:

object[] AllFiles = new DirectoryInfo(path).GetFiles().ToArray();

use

List<string> AllFiles = new DirectoryInfo(path).GetFiles().ToList();
MyDataGrid.ItemSource = Allfiles;

This will automatically bind the files to the DataGrid.



回答5:

string [] fileEntries = Directory.GetFiles(targetDirectory);

List<FileInfo> fileList = new List<FileInfo>();

foreach (string file in fileEntries)
{

fileList.Add(new FileInfo(file));
}

datagrid.ItemsSource = fileList;