wpftypesbindingresourcesdatatemplate

simple wpf binding with datatemplate according to datatype


I have what seems to be a very easy WPF question for some people. I'm not totally new to WPF, but not pro neither.

Trying to bind a contentcontrol to the selected item of a treeview. Did search many posts, and that was what seemed to work for other people, but can't manage to get the datatemplate to show something according to the datatype.

<ContentControl  Grid.Column="1" Grid.RowSpan="3" Grid.ColumnSpan="2" DataContext="{Binding SelectedItem, ElementName=DataManagerTreeView, Mode=OneWay}">
            <ContentControl.Resources>
                <DataTemplate DataType="{x:Type daq:DAQChartChannel}">
                    <StackPanel Orientation="Vertical">
                        <Label>Name</Label>
                        <Label Content="{Binding Name}"></Label>
                        <Label>AxisX</Label>
                        <Label Content="{Binding AxisX}"></Label>
                        <Label>AxisY</Label>
                        <Label Content="{Binding AxisY}"></Label>
                    </StackPanel>
                </DataTemplate>
                <DataTemplate DataType="{x:Type daq:DAQChart}">
                    <StackPanel Orientation="Vertical">
                        <Label>Name</Label>
                        <Label Content="{Binding Name}"></Label>
                    </StackPanel>
                </DataTemplate>
                <DataTemplate DataType="{x:Type daq:DAQChartsCollection}">
                    <StackPanel Orientation="Vertical">
                        <Label>Name</Label>
                        <Label Content="{Binding Name}"></Label>
                    </StackPanel>
                </DataTemplate>
            </ContentControl.Resources>
        </ContentControl>

If put the a single stackpanel directly withing my ContentControl, it shows the data of the current selected item right (at least the name which is the only one present in all items types) so the binding is correct. But when I try to use the ContentControl.Resources to show data according to the source type with DataTemplates, I don't get any output. Am I missing something here?

Is there no other workaround than using an DataTemplateSelector ? Thanks for the help


Solution

  • You have to bind the Content property of the ContentControl instead of its DataContext.

    Also note that Mode=OneWay in the Binding declaration is redundant.

    <ContentControl ...
        Content="{Binding SelectedItem, ElementName=DataManagerTreeView}">