以编程方式指定元素名称
本文关键字:元素 编程 方式指 | 更新日期: 2023-09-27 18:33:33
我正在尝试为每个元素添加一个从循环中获得的唯一名称。我怎样才能完成它?第 2 行是错误所在。
foreach (var station in stations) {
TextBlock station.name = new TextBlock(); // error !!!
}
试试这个...
TextBlock station = new TextBlock() { Name="Something" };
也许我误解了你想做什么... 是否正在尝试为集合的每个成员创建控件? 如果这就是您正在执行的操作,请尝试查看 ListBox 或更通用的 ItemsPresenter 控件以及该元素的 ItemTemplate 属性。
例如,将列表框添加到 XAML,并将工作站指定为项源,然后添加数据模板来表示项。
<ListBox ItemsSource="{Binding stations}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
您尝试在文本块实例站的 name 属性上创建新的文本块实例。
这绝对行不通。
尝试:
TextBlock station = new TextBlock();
station.name = "Whatever name you want";