Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataTemplate Binding

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();
        }
    }
}
like image 763
ejones Avatar asked Dec 26 '22 07:12

ejones


2 Answers

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>
like image 83
Sheridan Avatar answered Dec 27 '22 20:12

Sheridan


<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 ;)

like image 42
Miiite Avatar answered Dec 27 '22 21:12

Miiite