Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add SubItems to ListView without using XAML

How do you add sub-items to a ListView? I need to generate everything dynamically, but every example I've found uses XAML.

Non-WPF was so simple:

ListViewItem lvi = listview.items.add(wahtever);
lvi. blah blah blah

How do you add sub-items in WPF without using XAML?

like image 517
nitefrog Avatar asked Dec 22 '22 19:12

nitefrog


2 Answers

As already mentioned, WPF doesn't have sub-items like WinForms. Instead you use properties on an object that suits your purposes.

For completeness, here is XAML contrasted with code.

XAML:

    <UniformGrid Columns="2">
        <ListView Name="xamlListView">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="X Value" DisplayMemberBinding="{Binding X}"/>
                    <GridViewColumn Header="Y Value" DisplayMemberBinding="{Binding Y}"/>
                </GridView>
            </ListView.View>
            <ListView.Items>
                <PointCollection>
                    <Point X="10" Y="20"/>
                    <Point X="20" Y="30"/>
                </PointCollection>
            </ListView.Items>
        </ListView>
        <ListView Name="codeListView"/>
    </UniformGrid>

Code:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        var view = new GridView();
        view.Columns.Add(new GridViewColumn { Header = "First Name", DisplayMemberBinding = new Binding("First") });
        view.Columns.Add(new GridViewColumn { Header = "Last Name", DisplayMemberBinding = new Binding("Last") });
        codeListView.View = view;
        codeListView.Items.Add(new { First = "Bill", Last = "Smith" });
        codeListView.Items.Add(new { First = "Jane", Last = "Doe" });
    }
like image 76
Rick Sladkey Avatar answered Feb 01 '23 15:02

Rick Sladkey


The "WPF way" would be to bind your listview to a collection that represents the data you want to display. Then add objects containing data to that collection. You almost never should have to deal with adding ListViewItems to your list manually as you are planning to do. I could come up with an example but there's many threads here on SO already that solve exactly this problem:

  1. Add programmatically ListViewItem to Listview in WPF
  2. WPF ListView - how to add items programmatically?
like image 41
BrokenGlass Avatar answered Feb 01 '23 13:02

BrokenGlass