WPF ListView - how to add items programmatically?
Asked Answered
A

2

29

Even if I know it's not ideal - I need to programmatically populate a listView (for whatever reason).

I am declaring my columns in the markup:

            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=Name}"/>
                    <GridViewColumn Header="Value" DisplayMemberBinding="{Binding Path=Value}"/>
                </GridView>
            </ListView.View>

I am adding the items like this in code (it's obviously in a loop):

            MyData data = getDataItem(index); //< -- whatever
            ListViewItem item = new ListViewItem();
            item.DataContext = data;
            this.myListView.Items.Add(item);

Where MyData is defined as:

public class MyData
{
    public string Name { get; set; }
    public string Value { get; set; }
}

The items are being added (I can see the rows) but I don't see any content.

Anyone any clue?

Any help appreciated!

Anatolia answered 20/8, 2009 at 11:0 Comment(0)
A
37

It works changing the code to:

        MyData data = getDataItem(index); //< -- whatever
        this.myListView.Items.Add(data);

Now it looks obvious but ... go figure!

Anatolia answered 20/8, 2009 at 11:21 Comment(2)
Do you also happen to know how to solve the same issue, having a general list, that can take different objects, with different properties?Austerity
WOw another Persie fan here OR Persie can code! :) anyways, thx @RobinVanPersiMelodymeloid
S
0
List<MyData> yourList= new List<MyData>();
//adding elements to yourList (...)


foreach (MyData m in yourList)
{
    myListView.Items.Add(m);
}
Stigmatic answered 8/2, 2023 at 20:46 Comment(1)
Who voted this down, rather: why??? This seems a useful answer. I'd like to learnDich

© 2022 - 2024 — McMap. All rights reserved.