WPF ListView - 如何以编程方式添加项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1305406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:53:30  来源:igfitidea点击:

WPF ListView - how to add items programmatically?

wpflistviewlistviewitempopulate

提问by JohnIdol

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

即使我知道这并不理想 - 我需要以编程方式填充 listView (无论出于何种原因)。

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:

其中 MyData 定义为:

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!

任何帮助表示赞赏!

回答by JohnIdol

It works changing the code to:

它可以将代码更改为:

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

Now it looks obvious but ... go figure!

现在看起来很明显但是......去图!