4
votes

I discovered when using a ContentTemplate/DataTemplate in a WPF TabControl my Bindings will not work anymore.

I have set up a small example to illustrate:

<Window x:Class="HAND.BindingExample"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="BindingExample" Height="506" Width="656"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    >
<Grid>
    <TabControl HorizontalAlignment="Left" Height="381"  VerticalAlignment="Top" Width="608">
        <TabItem Header="TabItem">
            <Label Content="{Binding Path=myString}"/>
        </TabItem>
        <TabItem Header="TabItem">
            <TabItem.ContentTemplate>
                <DataTemplate>
                    <Label Content="{Binding Path=myString}"/>
                </DataTemplate>
            </TabItem.ContentTemplate>
        </TabItem>
    </TabControl>
</Grid>
</Window>

Tab1 works as expected, Tab2 is empty.

the code behind:

using System.Windows;

namespace HAND
{
    public partial class BindingExample : Window
    {
        public string myString { get; set; }

        public BindingExample()
        {
            myString = "Hello Stackoverflow";

            InitializeComponent();
        }
    }
}
2

2 Answers

6
votes

You are using the ContentTemplate property incorrectly. From the ContentControl.ContentTemplate Property page on MSDN:

Gets or sets the data template used to display the content of the ContentControl.

Therefore, when setting this property, you also need to set the Content property to some sort of data source:

<TabControl>
    <TabItem Header="TabItem">
        <Label Content="{Binding Path=myString}"/>
    </TabItem>
    <TabItem Header="TabItem" Content="{Binding Path=myString}">
        <TabItem.ContentTemplate>
            <DataTemplate>
                <Label Content="{Binding}" />
            </DataTemplate>
        </TabItem.ContentTemplate>
    </TabItem>
</TabControl>
4
votes
<TabItem Content="{Binding myString}" Header="TabItem">
    <TabItem.ContentTemplate>
        <DataTemplate>
            <Label Content="{Binding}" />
        </DataTemplate>
    </TabItem.ContentTemplate>
</TabItem>

But just so you know, to bind a window on itself, is just not the way to go. I don't know if you did that just for the example, but if not try and create a proper viewModel to bind your window on ;)