我发现当在WPF TabControl中使用ContentTemplate/DataTemplate时,我的绑定将不再起作用。
我设置了一个小例子来说明:
我设置了一个小例子来说明:
<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正常工作,Tab2为空。
背后的代码:
using System.Windows;
namespace HAND
{
public partial class BindingExample : Window
{
public string myString { get; set; }
public BindingExample()
{
myString = "Hello Stackoverflow";
InitializeComponent();
}
}
}
myString
属性数据绑定到Content
属性,以给它一些值。在这里,该值只是一个单独的字符串,但它也可以是带有其他属性的对象。在ContentTemplate
中,我们告诉它我们想要在Label
中显示数据绑定对象的哪个部分。在这种情况下,我们想要绑定整个字符串对象,所以我们使用{Binding}
来实现。 - Sheridan