Search code examples
c#wpfuser-controlsitemtemplate

WPF Automaticly list Items from Context


Let's say I have a class A. I already created a UserControle X that uses A as DataContext. Now there is Class B. Class B contains nothing but a List filled with instances of A. An Instance of B is the DataContext of my current View.

What's the best way to show for all Instances of A in the list of the current DataContext a Usercontrole X?

Do I need a Value Converter? Or is there an easier way.

I tried to keep it abstract. If I need to specify certain things please let me know.


Solution

  • You could use an ItemsControl with an ItemTemplate. Bind the ItemsControl to the public collection property, and add the UserControl to the ItemTemplate:

    <ItemsControl ItemsSource="{Binding TheListProperty}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <!-- The UserControl will inherit the current item in 'TheListProperty' as its DataContext -->
                <local:UserControlX />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    

    Make sure that you don't explicitly set the DataContext of the UserControl. It should inherit its DataContext from the current item in the ItemsControl.