Adding items to a ListView in C# in a WPF application

混江龙づ霸主 提交于 2021-01-28 19:07:26

问题


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 " "?


回答1:


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.

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

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; }
}

Then replace this:

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);
}

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>


来源:https://stackoverflow.com/questions/31882264/adding-items-to-a-listview-in-c-sharp-in-a-wpf-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!