Add SubItems to ListView without using XAML

17,506

Solution 1

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

Solution 2

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?
Share:
17,506
nitefrog
Author by

nitefrog

BY DAY: Envangilze open source technologies and roll up the sleeves to play! BY NIGHT: Write poetry and short stories into the wee hours of the morning. FOR FUN: Read a ton, live a lot, and drink as much coffee as I am humanly able.

Updated on June 09, 2022

Comments

  • nitefrog
    nitefrog almost 2 years

    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?