我搜索了很多主题,但找不到有关使用 WPF DataGrid
列出目录中的文件名内容的答案。我能够在 ListBox
中输出内容,但不知道如何将项目添加到 DataGrid
中的 Column
。
这适用于 ListBox
string path = "C:";
object[] AllFiles = new DirectoryInfo(path).GetFiles().ToArray();
foreach (object o in AllFiles)
{
listbox.Items.Add(o.ToString());
}
如何对 DataGrid
执行相同的操作?或者至少将 array
中的 strings
放入 DataGrid
Column
中?
最佳答案
您可以创建具有一列的 DataGrid
:
<DataGrid x:Name="myDataGrid" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True" Binding="{Binding}" Header="Name"/>
</DataGrid.Columns>
</DataGrid>
然后像这样填写你的代码:
myDataGrid.ItemsSource = new DirectoryInfo(path).GetFiles();
通过将 ItemsSource
设置为 FileInfo[]
,您可以选择创建绑定(bind)到 FileInfo
类其他属性的其他列。此 DataGrid
将与分配给 ItemsSource
的任何 IEnumerable
一起使用。如果它还不是一个 string
,那么将调用 ToString()
关于c# - 列出 DataGrid 中的目录文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18474761/