WPF - Databind to a StackPanel using DataTemplates

Ronald picture Ronald · Jul 20, 2009 · Viewed 19.6k times · Source

I've modified my question since it has changed focus when trying things out. I narrowed the problem down to the following...

I try to bind the selected Item of a TreeView to a StackPanel (or some other container that can hold User Controls). This container will then display a UserControl, depending on the type of the selected item.

Here is the xaml of the StackPanel (both treeview and stackpanel are in the same window ==> different grid column)

<StackPanel Grid.Column="2" MinWidth="500" DataContext="{Binding ElementName=myTree, Path=SelectedItem, Mode=OneWay}">
    <StackPanel.Resources>
        <DataTemplate DataType="{x:Type mvTypes:MyTypeA}">
            <controls:UserControlA DataContext="{Binding}" />
        </DataTemplate>
        <DataTemplate DataType="{x:Type mvTypes:MyTypeB}">
            <controls:UserControlB DataContext="{Binding}" />
        </DataTemplate>
    </StackPanel.Resources>
</StackPanel>

When I place a user control directly under the stackpanel (not in the resources), it displays it with the selected object as their datacontext. Idem if I place a TextBox in it, it will show the correct type of the selected item.

<TextBox Name="textBox1" Text="{Binding}" />

For some reason, placing it within a DataTemplate (even without setting the DataType) results in nothing to display.

Any sugestions. I'm thinking that maybe a StackPanel is not the right control for this, though I can't seem to find other controls that look suitable as containers like this.

Thanks in advance.

Answer

Bryan Anderson picture Bryan Anderson · Jul 20, 2009

Replace the StackPanel in your example with ContentPresenter and instead of DataContext set the Content property. That should work.