开发者

How To Add Subitem in ListViewItem in WPF C#

开发者 https://www.devze.com 2023-04-03 21:08 出处:网络
I want to import data From excel datasheet to listview in WPF. I want to add item and subitem to listviewitem.

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("");}
    }
   List开发者_如何学JAVAView.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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号