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 <
string [] fileEntries = Directory.GetFiles(targetDirectory);
List<FileInfo> fileList = new List<FileInfo>();
foreach (string file in fileEntries)
{
fileList.Add(new FileInfo(file));
}
datagrid.ItemsSource = fileList;
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>
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
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.
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.