c# - 列出 DataGrid 中的目录文件

标签 c# wpf wpfdatagrid .net

我搜索了很多主题,但找不到有关使用 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/

相关文章:

c# - 创建 C# 绑定(bind)

wpf - 如何显示菜单项的工作键盘快捷键?

VSTS : Different checksum values given for '*.g.cs' Files 的 WPF 警告

c# - 为什么这个 MultiDataTrigger 会在动画上抛出异常?

c# - 当绑定(bind)到 WPF DataGrid 时,包装的 ObservableCollection<T> 抛出 `' EditItem' is not allowed for this view`

c# - 我怎么知道我的应用程序窗口是前景窗口

c# - WinRT 投影类型文档

c# - 标题栏的上下文菜单

c# - 突出显示 WPF 数据网格中的单元格时没有可见文本

c# - 按项目模板中的多个项目排序