Search code examples
wpfxamlmvvmdesktop-application

How to iterate collection in XAML, where the collection is part of the model in c# class


I am building desktop application using WPF and XAML with MVVM pattern. I have a collection of strings ( error messages) in the model class. Class is binded to the XAML. I need to iterate the collection of strings so that they are displayed in bullet points in the view.

I have tried itemscontrols tag, but no luck with it. It just displays the first element of the list.

I expected that collection will be iterated but only the first element of the collection is displayed. There are no error messages.


Solution

  • The usual way to render a list of anything in WPF/MVVM is with an ItemsControl:

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

    If you don't like the default item representation then you can override the item template:

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

    Result:

    enter image description here

    You can also override the default ItemPanel if you want the items to be laid out different i.e. WrapPanel, horizontal StackPanel etc.