如何在XAML中迭代集合,其中集合是c#类中模型的一部分

时间:2019-05-19 21:33:56

标签: wpf xaml mvvm desktop-application

我正在使用WPF和XAML和MVVM模式构建桌面应用程序。 我在模型类中有一个字符串(错误消息)集合。类已绑定到XAML。我需要迭代字符串的集合,以便在视图的项目符号点中显示它们。

我尝试了itemscontrols标记,但运气不佳。它只是显示列表的第一个元素。

我希望将迭代集合,但是仅显示集合的第一个元素。没有错误消息。

1 个答案:

答案 0 :(得分:2)

在WPF / MVVM中呈现任何内容列表的通常方法是使用ItemsControl:

<ItemsControl ItemsSource="{Binding MyItems}" />

如果您不喜欢默认的项目表示形式,则可以覆盖项目模板:

<ItemsControl ItemsSource="{Binding MyItems}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=., StringFormat={}&#8226;{0}}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

结果:

enter image description here

如果您希望项目以不同的方式布置,例如WrapPanel,水平StackPanel等,也可以覆盖默认的ItemPanel。