且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何绑定列表< String>到StackPanel

更新时间:2022-05-02 02:48:20

要将枚举对象绑定到控件并显示它们,可以使用任何 ,您可以在其中进行进一步修改以更改商品的容器.在大多数情况下,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 ItemsControls 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.