c# - 如何从返回 List 的 Object 方法动态创建内容(标签/网格)
问题描述
我试图搜索谷歌以获得答案,但我似乎无法以正确的方式提出问题,因此没有一个答案能描述我的问题。
问题是:我想根据 Object 方法的结果创建未知数量的控件(网格、文本框、标签 {pick one} - 这对这个示例无关紧要。我稍后会出于我的目的对其进行编辑)返回List<string>
。假设该方法返回带有 4 个项目的列表,因此在应用程序启动时,我希望看到四个标签/文本框(行中)以及列表中的文本。
我正在学习 WPF,所以我做了一些教程等,我能够将对象中的值绑定到单个标签/文本框/控件,但不知道如何动态地使用列表项的整个结果。
我什至无法想象,所以很难将其更改为代码。
假设我有以下对象:
namespace Test
{
public class Robots
{
public List<string> GetAllRobots()
{
List<string> resultList = new List<string>();
resultList.add["Robot1"];
resultList.add["Robot2"];
resultList.add["Robot3"];
resultList.add["Robot4"];
return resultList;
}
}
}
这是我不知道如何构建以将四个单独的标签生成/绑定到 XAML 中的部分。
namespace Test
{
/// <summary>
/// Interaction logic for UCRobots.xaml
/// </summary>
public partial class UCRobots : UserControl
{
public UCRobots()
{
InitializeComponent();
List<string> dataList = new Robots().GetAllRobots();
this.DataContext = dataList;
}
}
}
是否有任何教程如何编写您可以指出我的 XAML 部分?或者任何愿意帮助我回答的人?
解决方案
您可以使用任何类型的 ItemsControl 来显示集合的内容。一些示例是 ListBox、TreeView、HeaderedItemsControl、TabControl,甚至是 ItemsControl 本身。这些控件采用项目列表并根据 ItemTemplate 显示它们。
在您的示例中,您将编辑 UCRobots.xaml 文件以具有以下内容
<!-- The ItemsSource property defines the list of items.
Here we are binding directly to the DataContext of the UCRobots class.
You could also bind to a property of the object that is set as the DataContext -->
<ItemsControl ItemsSource="{Binding}">
<!--
The below is commented out because the default DataTemplate for the ItemTemplate
property is to display a TextBlock that binds directly to the item
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
The Text property is binding directly to the item in the list.
If your list contained objects with properties, you could bind to one of those properties.
For example, if your list contained a list of People objects, you could bind the
Text property to the Name property of your class
</DataTemplate>
</ItemsControl.ItemTemplate>
-->
</ItemsControl>
推荐阅读
- r - 无法在 R 中安装 DPpackage
- javascript - jsp 包含 jsp 不重新加载菜单导航栏
- postgresql - 如何在时间范围内添加唯一约束?
- python - 根据第一个元素从列表列表中仅返回唯一出现
- android - 当我从 XML 和代码设置 textField 的属性时,什么会优先考虑?
- android - 如何强制Android应用程序后台刷新?
- python - Docker Compose Django 和 PostgreSql 出错
- sql - 用同一列中的匹配值替换空日期值?
- python - 将向量(数组 1D)插入二维数组?
- java - 垃圾收集器是否在从 C++ 创建的 JVM 中运行?