WPF - Databind to a StackPanel using DataTemplates

不羁岁月 提交于 2019-12-03 11:57:10

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

Although you have set the Binding on the second custom control, are you setting the DataContext, as the binding is the route to the information and the DataContext is the information it applies this binding information to.

Andrew

Kenan E. K.

You can create a UserControl to display the TreeView and the selection info on the right, all in one. It saves you from creating any custom control. A custom control is basically unnecessary since you do not create anything which didn't exist before.

<UserControl x:Class="NameSpace.SelectionView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="namespace.Controls"
    Height="300" Width="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <TreeView Name="customTree">
            <!--Items go here-->
        </TreeView>
        <StackPanel Grid.Column="1" MinWidth="50" DataContext="{Binding ElementName=customTree, Path=SelectedItem, Mode=OneWay}">
            <StackPanel.Resources>
                <DataTemplate DataType="{x:Type StylingTest:CustomViewModelA}">
                    <controls:CustomADetailsControl />
                </DataTemplate>
                <DataTemplate DataType="{x:Type StylingTest:CustomViewModelB}">
                    <controls:CustomBDetailsControl />
                </DataTemplate>
            </StackPanel.Resources>
            <TextBlock Text="{Binding}"/>
        </StackPanel>
    </Grid>
</UserControl>

Any other custom behaviour, I'm sure you could create or set in styles/templates here.

Also, you might find one of my other answers useful.

Good luck with wpf, cheers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!