WPF ListView - how to add items programmatically?

倖福魔咒の 提交于 2019-11-27 03:05:25

问题


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!


回答1:


It works changing the code to:

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

Now it looks obvious but ... go figure!



来源:https://stackoverflow.com/questions/1305406/wpf-listview-how-to-add-items-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!