如何绑定列表<String>到 StackPanel [英] How Can You Bind a List<String> to a StackPanel
问题描述
在我的应用程序中,我有一个 string
的 List
,但是我不知道如何/不知道如何将此列表绑定到 <代码>堆栈面板代码>.
In my application I have a List
of string
s, however I can't find out how to/don't know how to bind this list to a StackPanel
.
我尝试过使用 ListBox
,但是 ListBox
的滚动特性对我的应用程序的用户来说非常不方便.
I've tried using a ListBox
but the scrolling nature of the ListBox
is very inconvenient to the user of my application.
那么有谁知道我如何将 string
的 List
绑定到 StackPanel
?
So does anyone know how I could bind a List
of string
s to a StackPanel
?
我试过弄乱几个属性,但没有找到任何东西.
I have tried messing around with several properties but haven't found anything.
感谢您的帮助!
推荐答案
要将枚举绑定到控件并显示它们,您可以使用任何 ItemsControl
并将您的对象绑定到 ItemsSource
属性.ItemsControl
公开了一个名为 ItemsPanel
,您可以在其中进一步修改以更改项目的容器.StackPanel
是大多数的默认设置.
To bind an enumerable to a control and have them displayed, you can use any of the ItemsControl
and bind your object to the ItemsSource
property. The ItemsControl
s expose a property called ItemsPanel
in which you can further modify to alter the container for the items. StackPanel
is the default in most of them.
<ItemsControl ItemsSource="{Binding NewbieList}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<!-- The default for an ItemsControl is a StackPanel with a vertical orientation -->
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
至于您的评论,ItemsSource
中的任何内容都将输出"ItemTemplate
属性中的内容(默认基本上是一个 TextBlock
绑定到 DataContext
的文本).对于每个元素,DataContext
将是列表中的项目.例如,如果你有一个 string
的列表,你可以这样做:
As for your comment, anything within the ItemsSource
will "output" what's in the ItemTemplate
property (the default is basicaly a TextBlock
with the text bound to the DataContext
). For each elements, the DataContext
will be the item in the list. If you have a list of string
, for example, you can do:
<!-- Rest is omitted for succinctness -->
<ItemsControl>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding .}" FontSize="26" MouseDown="yourEventHandler"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl>
或者,如果您只想更改字体大小,您可以使用 ItemsControl
本身的 TextElement.FontSize
依赖属性或设置 ItemsContainer 的样式代码>:
Alternatively, if all you want is the font size to change, you can use the TextElement.FontSize
Dependency Property on the ItemsControl
itself or style the ItemsContainer
:
<ItemsControl TextElement.FontSize="26">
<!-- Rest omitted for succinctness -->
</ItemsControl>
或者:
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="TextElement.FontSize" Value="26"/>
</Style>
</ItemsControl.ItemContainerStyle>
我建议您阅读有关 WPF 中绑定和项目控制的文章/教程,以获取有关如何执行各种任务的更多信息,有很多要解释的内容.
I suggest you read articles / tutorials on binding and items control in WPF for more information on how to do various tasks, there is alot to explain.
这篇关于如何绑定列表<String>到 StackPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!