Christian Aehnelt
Christian Aehnelt

Reputation: 60

Set DataTemplate by ElementName

i have some issues with binding ContentControl to ListboxItem.

This is my ListBox.

<ListBox x:Name="box">
     <ListBoxItem Tag="{x:Type vm:PART_FAMILY_ViewModel}" Content="Car"></ListBoxItem>
     <ListBoxItem Tag="{x:Type vm:PART_TYPES_ViewModel}" Content="Bike" IsSelected="True"></ListBoxItem>
</ListBox>

This is my ContenControl:

<ContentControl Content="{Binding ElementName=box, Path=SelectedItem.Tag}">
    <ContentControl.Resources>

    <DataTemplate DataType="{x:Type vm:PART_FAMILY_ViewModel}">
        <v:PART_FAMILYS_View></v:PART_FAMILYS_View>
    </DataTemplate>

    <DataTemplate DataType="{x:Type vm:PART_TYPES_ViewModel}">
        <v:PART_TYPES_View></v:PART_TYPES_View>
    </DataTemplate>

    </ContentControl.Resources>
</ContentControl>

With my Elementname i only see the Tag DataType in my ContentControl.

Upvotes: 1

Views: 47

Answers (1)

mm8
mm8

Reputation: 169160

With my Elementname i only see the Tag DataType in my ContentControl.

That's because you set the Tag property to a type. You should set it to an instance of the type for the DataTemplate to get applied as expected:

<ListBox x:Name="box">
    <ListBoxItem Content="Car">
        <ListBoxItem.Tag>
            <vm:PART_FAMILY_ViewModel />
        </ListBoxItem.Tag>
    </ListBoxItem>
    <ListBoxItem Content="Bike" IsSelected="True">
        <ListBoxItem.Tag>
            <vm:PART_TYPES_ViewModel />
        </ListBoxItem.Tag>
    </ListBoxItem>
</ListBox>

Upvotes: 1

Related Questions