jgraham
Topic Author
Posts: 6
Joined: 24 Sep 2014, 21:08

Dynamically adding a UserControl to a ListBox

24 Sep 2014, 21:27

What is the best way to add multiple different UserControls to a ListBox at runtime? Do I need to always use a DataModel when adding lines to a ListBox? Here are some options that I can think of:

1. Tie each unique UserControl to a DataTemplate. I don't think this approach is possible because the DataModel approach assumes each item uses the same DataTemplate.
2. Add UserControls to a ListBox without using a DataModel or DataTemplate.
3. I could ditch the ListBox entirely and use a StackPanel, but I would like to have a scroll capability, so I don't think that approach will work.
4. Is there a way to apply different styles to separate ListBox items?


Here are the requirements that I am attempting to satisfy:
1. The list shall have the capability of displaying different GUI elements on each line
2. The GUI elements may vary in size
3. The list shall be editable at runtime
4. The list shall be scrollable
 
MrHayato
Posts: 36
Joined: 19 Sep 2014, 21:29

Re: Dynamically adding a UserControl to a ListBox

24 Sep 2014, 22:23

StackPanel is the way to go. Just wrap it in a ScrollViewer control. I am actually doing this exact scenario in our project. You can always edit the stackpanel contents at runtime too in the code-behind.
 
User avatar
sfernandez
Site Admin
Posts: 1920
Joined: 22 Dec 2011, 19:20

Re: Dynamically adding a UserControl to a ListBox

25 Sep 2014, 21:35

Hi,

You can specify a different DataTemplate for each data type you add to the ListBox. Instead of setting the ItemTemplate property, let the resource lookup to assign the correct template:
<Grid>
    <Grid.Resources>
        <DataTemplate TargetType="local:Cat">...</DataTemplate>
        <DataTemplate TargetType="local:Dog">...</DataTemplate>
        ...
    </Grid.Resources>

   <ListBox ItemsSource="{Binding Animals}"/>

</Grid>
Animals will be a collection of different animals: Cat, Dog, ...
Each item of the ListBox will use the corresponding DataTemplate.

Is that what you need?
 
jgraham
Topic Author
Posts: 6
Joined: 24 Sep 2014, 21:08

Re: Dynamically adding a UserControl to a ListBox

25 Sep 2014, 22:26

I will look into it, right now I am trying the StackPanel approach. Either approach sounds like it will work. I also saw something about using a DataTemplateSelector here (viewtopic.php?f=3&t=333&p=2699#p2699). But it appears to not be implemented. Is that still the case?

Thanks for the help!
 
User avatar
sfernandez
Site Admin
Posts: 1920
Joined: 22 Dec 2011, 19:20

Re: Dynamically adding a UserControl to a ListBox

29 Sep 2014, 16:22

Sorry, but DataTemplateSelector is not yet exposed to Unity as explained here: viewtopic.php?f=3&t=333&p=2708#p2708

Who is online

Users browsing this forum: No registered users and 1 guest