如何绑定列表< String>到StackPanel [英] How Can You Bind a List<String> to a StackPanel
问题描述
在我的应用程序中,我有List
个string
s,但是我无法找到如何/不知道如何将该列表绑定到StackPanel
.
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.
感谢您的帮助!
推荐答案
要将枚举对象绑定到控件并显示它们,可以使用任何 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屋!