Add SubItems to ListView without using XAML

nitefrog picture nitefrog · Jan 14, 2011 · Viewed 16.9k times · Source

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?

Answer

Rick Sladkey picture Rick Sladkey · Jan 14, 2011

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