Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display List of Custom Objects in a ListBox, Using a Custom User Control For Each

I have a list of objects (a custom class) that I want to display inside a ListBox, with each object drawing inside a custom User Control. Imagine a list of contacts (with custom Contact class) that should show up as a list of ContactUserControls (the XAML designed to present a Contact)

I know how to databind a list of Contact objects to a ListBox. I can databind a single Contact to a single ContactUserControl. I'm trying to understand the pattern/implementation of a databound list of objects that uses my custom UserControl to draw each object.

Do I bind the ListBox to my list of Contact objects, and (inside the Contact class) set up a connection to the ContactUserControl ("This is how you draw")? Do I bind the ListBox to a list of ContactUserControls, and bind each User Control to one of theses Contact objects before they go into the list? If so, do I have to do it manually via "ForEach" binding, or is there a "semi-magical" way in which it can be done purely via XAML?

Ideally, everything is correctly databound. Thanks! Not expecting somebody to present a turnkey solution of the entire thing, pointers to the applicable pattern/tutorials would be a great start.

like image 968
Drakestar Avatar asked Sep 11 '25 05:09

Drakestar


1 Answers

You can use <ListBox.ItemTemplate>. Something like this:

<ListBox ItemsSource="{Binding contacts}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <local:ContactUserControls DataContext="{Binding}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

See https://msdn.microsoft.com/en-us/library/cc265158(v=vs.95).aspx the section about To format items in a ListBox or see https://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemtemplate(v=vs.110).aspx the Examples section

like image 186
Pouya Abadi Avatar answered Sep 13 '25 19:09

Pouya Abadi