Dynamically load various UserControls based on object type through data binding in xaml

Is there any way in WPF to get the same functionality as a DataTemplateSelector , but for UserControls?

Say I have a StackView to which I want to bind IEnumerable objects. What I would like to do is somehow have a mapping that, for each type of object in the linked IEnumerable, looks at the type of the object and determines what UserControl will add to the StackView.

So, given the three classes:

 public class House : Building{} public class Apartment : Building{} public class Tent : Building{} 

where each class inherits from Building and has its own specific UserControl , I would like to set the DataContext to IEnumerable<Building> and somehow make the StackView populate its set of child elements with the UserControl type.

I would like to do this with as little code as possible. The more data binding and XAML clone ribbon, the better.

+4
source share
2 answers

You can use complex user controls in a DataTemplate ; just declare the DataTemplate as your UserControl .

Example:

  <Window x:Class="WpfApplication4.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication4" Title="MainWindow" Height="300" Width="300" Name="UI" > <Window.Resources> <DataTemplate DataType="{x:Type local:House}" > <local:HouseUserControl DataContext="{Binding}"/> </DataTemplate> <DataTemplate DataType="{x:Type local:Apartment}"> <local:ApartmentUserControl DataContext="{Binding}"/> </DataTemplate> </Window.Resources> <Grid> <ListBox ItemsSource="{Binding ElementName=UI, Path=ListOfBuildings}" /> </Grid> </Window> 
+6
source

I'm not sure I see the problem. Just create DataTemplates for each type in your resources somewhere, and WPF will use them automatically to display each type.

+2
source

All Articles