问题
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