Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - Databind to a StackPanel using DataTemplates

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.

like image 384
Ronald Avatar asked Jul 20 '09 07:07

Ronald


1 Answers

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

like image 156
Bryan Anderson Avatar answered Nov 05 '22 13:11

Bryan Anderson