WPF 数据模板绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24534021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF DataTemplate Binding
提问by ejones
I discovered when using a ContentTemplate/DataTemplate in a WPF TabControl my Bindings will not work anymore.
我发现在 WPF TabControl 中使用 ContentTemplate/DataTemplate 时,我的绑定将不再起作用。
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.
Tab1 按预期工作,Tab2 为空。
the code behind:
背后的代码:
using System.Windows;
namespace HAND
{
public partial class BindingExample : Window
{
public string myString { get; set; }
public BindingExample()
{
myString = "Hello Stackoverflow";
InitializeComponent();
}
}
}
回答by Sheridan
You are using the ContentTemplateproperty incorrectly. From the ContentControl.ContentTemplatePropertypage on MSDN:
您正在ContentTemplate错误地使用该属性。从MSDN 上的ContentControl.ContentTemplate属性页:
Gets or sets the data template used to display the content of the ContentControl.
获取或设置用于显示 ContentControl 内容的数据模板。
Therefore, when setting this property, you also need to set the Contentproperty to some sort of data source:
因此,在设置该属性时,还需要将该Content属性设置为某种数据源:
<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>
回答by Miiite
<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 ;)
但正如您所知,在自身上绑定一个窗口并不是要走的路。我不知道您是否只是为了示例而这样做,但如果不尝试创建一个合适的 viewModel 来绑定您的窗口;)

