-1

I have a UserControl that I made with a few Labels to show information from a custom class I wrote, that has fields which hold the data the Labels must display.

I will have a collection of objects of said class and I want to display them on my WPF window one below the other in a horizontal fashion.

I thought to use a StackPanel, as I don't know too much about WPF to think of other controls that could do that. So I looked around for a way to bind a collection to a StackPanel.

I found those questions: Q1, Q2 and Q3

However simply placing my UserControl in the DataTemplate doesn't work and I don't know how to tell WPF - take this collection of objects and tie each object to an instance of my UserControl and stack those in this StackPanel.

I would, rather strongly, prefer to use mainly XAML for this, so an answer with WPF Data Binding would be greatly appreciated, thank you!

J. Doe
  • 363
  • 2
  • 11
  • Use an ItemsControl and assign the DataTemplate to its ItemTemplate property. See [Data Templating Overview](https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/data-templating-overview). – Clemens Jan 31 '20 at 15:57

1 Answers1

0

You need to set the DataContext to a ViewModel which has your collection of custom objects (MyObjectcollection for instance), then just set up the bindings as follows:

<ItemsControl ItemsSource="{Binding MyObjectCollection}">
<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <StackPanel Orientation="Vertical" IsItemsHost="True"/>
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <MyUserControl />
    </DataTemplate>
</ItemsControl.ItemTemplate>

Dean Chalk
  • 20,076
  • 6
  • 59
  • 90
  • "*tie each object to an instance of my UserControl*" - The UserControl is supposed to be declared in the DataTemplate. In case the control exposes bindable properties, they should be bound to properties of the item, i.e. the "custom object". Otherwise the UserControl may also directly bind to that object, which would automatically be passed to its DataContext. So the DataTemplate would contain nothing but ``. Make sure however that the UserControl does not explicity set its own DataContext property. – Clemens Jan 31 '20 at 17:11
  • ive tweaked it, so the datatemplate uses your usercontrol – Dean Chalk Jan 31 '20 at 17:17