【问题标题】:How to iterate collection in XAML, where the collection is part of the model in c# class如何在 XAML 中迭代集合,其中集合是 c# 类中模型的一部分
【发布时间】:2019-05-19 21:33:55
【问题描述】:

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

我已经尝试过 itemscontrols 标签,但没有运气。它只显示列表的第一个元素。

我预计集合会被迭代,但只显示集合的第一个元素。没有错误消息。

【问题讨论】:

    标签: wpf xaml mvvm desktop-application


    【解决方案1】:

    在 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>
    

    结果:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-16
      • 2019-06-10
      • 2016-02-27
      • 1970-01-01
      相关资源
      最近更新 更多