I have a WPF listbox that houses a user control called JUC.
This works great and as I’m very new to WPF this already is very impressive. What I would like to do now is have different user controls in the list based upon a bound property.
Is this possible? If not, how else should I achieve this?
I’m using a list because I want to allow drop/drag ordering of the user controls, and there will be a variable number so seems to make sense – alternative approaches are welcome.
<ListBox x:Name="peopleListBox"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
ItemContainerStyle="{StaticResource ListBoxItemStretch}"
Foreground="Transparent"
BorderBrush="Transparent"
Background="Transparent"
Grid.ColumnSpan="2" SelectionChanged="peopleListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<my:JUC Margin="4"></my:JUC>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
You can use DataTemplateSelector, in SelectTemplate() method you can check which DataTemplate to use for currently passed in item:
In XAML:
In Code behind: