开发者

Add SubItems to ListView without using XAML

开发者 https://www.devze.com 2023-02-03 23:22 出处:网络
How do you add sub-items to a ListView? I need to generate everything dynami开发者_如何学JAVAcally, but every example I\'ve found uses XAML.

How do you add sub-items to a ListView? I need to generate everything dynami开发者_如何学JAVAcally, 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?


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


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?


SubItem or ListItem?? Easy:

myListbox.Items.Add(object);

You can add any type of object into that collection or a specific ListBoxItem object like this one:

this.List.Items.Add(new ListBoxItem{ Content = "Value to display"});
0

精彩评论

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

关注公众号