在WPF应用程序中将项目添加到C#中的ListView中

问题描述:

我想在磁盘上创建文件列表视图,以便在选择后进行进一步处理.因此,我使用列文件名,日期和大小创建了一个列表视图.然后,我使用以下函数加载listview:

I want to create a listview of files on the disk for further processing when selected. So I created a listview with the columns filename, date, and size. I then load the listview with the following function:

private void Window_Loaded(object sender, RoutedEventArgs e)  
{  
    foreach (string s in Directory.GetLogicalDrives())  
    {  
        filelist.Items.Add(s);   
    }  
}  

这列出了系统中要启动的驱动器,这很好,但是屏幕上显示的是

This lists the drives in the system to start which is fine, but what shows up on screen is

filename date size  
c:\      c:\  c:\  
d:\      d:\  d:\

所以,我的问题是,如何将子列的日期和大小设置为" " ?

So, my question is, how to I set subcolumns date and size to "" or " "?

您似乎有很多东西要学习,所以我只给您一些提示以帮助您入门,因为否则答案会太长.

You seem to have much to learn, so I'll just give you some clues to get you started, because otherwise this answer will be too long.

您有3列,每列都是从同一对象(字符串)获取数据.

You have 3 columns and each one is getting its data from the same object (the string).

创建一个新类,该类将保存您3列的数据:

Create a new class that will hold the data for your 3 columns:

class Drive
{
    public string Name { get; set; }
    public string Date { get; set; }
    public string Size { get; set; }
}

然后替换为:

foreach (string s in Directory.GetLogicalDrives())  
{  
    filelist.Items.Add(s);   
}

与此相关,它将生成数据项:

with this, which will generate the data items:

var drives = Directory.GetLogicalDrives().Select(d => new Drive { Name = d });

foreach (var drive in drives)
{
    MyListView.Items.Add(drive);
}

像这样设置您的 ListView ,以便每一列都从每个项目中自己的属性中获取数据:

Setup your ListView like this so that each column gets data from its own property in each item:

<ListView x:Name="MyListView">
    <ListView.View>
        <GridView>
            <GridView.Columns>
                <GridViewColumn Header="filename" DisplayMemberBinding="{Binding Name}"/>
                <GridViewColumn Header="date"  DisplayMemberBinding="{Binding Date}"/>
                <GridViewColumn Header="size"  DisplayMemberBinding="{Binding Size}"/>
            </GridView.Columns>
        </GridView>
    </ListView.View>
</ListView>