WPF DataTemplate Binding

痞子三分冷 提交于 2019-12-12 12:28:11

问题


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

回答1:


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>



回答2:


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



来源:https://stackoverflow.com/questions/24534021/wpf-datatemplate-binding

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