Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically load different UserControls based on object type via data binding in xaml

Is there some way in WPF to get the same functionality DataTemplateSelector gives you, but for UserControls?

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

So, given three classes:

public class House : Building{}

public class Apartment : Building{}

public class Tent : Building{}

where each class inherits from Building and has its own defined UserControl, I'd like to set DataContext to an IEnumerable<Building> and somehow get the StackView to populate its set of children with the type-specific UserControl.

I'd like to do this with as little code behind as possible. The more data binding and XAML duct tape the better.

like image 310
Turbo Avatar asked Jan 14 '23 20:01

Turbo


1 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>
like image 62
sa_ddam213 Avatar answered Jan 17 '23 08:01

sa_ddam213