C# WPF 为列表中的每个对象动态创建一个 GUI 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21730614/
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
C# WPF dynamically create a GUI element for each object in list
提问by xnonamex
I have a list of objects (same class). Each of these objects has couple of properties. I would like to build a GUI that would show a "tile" for each of these objects and in this "tile" the property values of this object would be displayed. The image bellow illustrates the idea.
我有一个对象列表(同一类)。这些对象中的每一个都有几个属性。我想构建一个 GUI 来为每个对象显示一个“磁贴”,在这个“磁贴”中将显示该对象的属性值。下图说明了这个想法。


By pressing on the + tile it would be possible to add new object (would bring up the dialogue). The object tiles would wrap to the next line allowing X tiles per line.
通过按 + 磁贴,可以添加新对象(将显示对话)。对象图块将换行到下一行,每行允许 X 个图块。
What would be your suggestions to do this in a civilized manner to be able to automatically add/remove tiles as an object in the list is created/deleted? Maybe someone knows some examples?
您对以文明的方式执行此操作有何建议,以便能够在创建/删除列表中的对象时自动添加/删除图块?也许有人知道一些例子?
Currently I'm quite blank on how to achieve this.
目前,我对如何实现这一目标一无所知。
回答by deloreyk
Consider using some sort of ItemsControlwith a DataTemplate. I would review the follow tutorial on how to do that: http://wpftutorial.net/DataTemplates.html
考虑使用某种ItemsControl有DataTemplate。我将查看有关如何执行此操作的以下教程:http: //wpftutorial.net/DataTemplates.html
As Matt Burland stated, you will need to put your objects into a ObservableCollectionfor them to appear "dynamically".
正如 Matt Burland 所说,您需要将对象放入 a 中,ObservableCollection以便它们“动态地”出现。
回答by czuroski
Please refer to this post -
请参考这篇文章——
it outlines using a ItemsControl with wrap panel create a tile effect. Hope that helps.
它概述了使用带有包装面板的 ItemsControl 创建平铺效果。希望有帮助。
回答by Koscik
1) Use a ListBox, bind ItemsSource property to your List. 2) Insert whatever kind of object you like in that list. 3) Create DataTemplate for each kind of object to display
1) 使用 ListBox,将 ItemsSource 属性绑定到您的列表。2) 在该列表中插入您喜欢的任何类型的对象。3)为每种要显示的对象创建DataTemplate

