I want to import data From excel datasheet to listview in WPF. I want to add item and subitem to listviewitem. If in Windows Form code:
foreach(DataRow drow in dtblImport.Rows)
{
ListViewItem lvi = new ListViewItem();
lvi.DataContext = drow[0].ToString();
foreach(DataColumn dcol in dtblImport.Column)
{
if(drow[dcol.Ordinal] != DBNull.Value){
lvi.SubItem.Add(drow[dcol.Ordinal].ToString());}
else {
lvi.SubItem.Add("");}
}
ListView.Items.Add(lvi);
}
But how if i want do it in WPF? Thanks
Define this control in your XAML
<ListView x:Name="listView">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=Name}" />
<GridViewColumn Header="Description" DisplayMemberBinding="{Binding Path=Description}" />
</GridView>
</ListView.View>
</ListView>
and then in the code-behind you can add new items to the List view by typing:
listView.Items.Add(new Item());
And the class Item contains the properties Name and Description.
If you want to change the columns shown, then change the XAML.
This is not a good approach, as here you aren't using MVVM, what you should do is bind the ListView ItemsSource property to a collection in your ViewModel, and then work over that collection.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.