我有以下用户控件:
<TabItem
x:Name="Self"
x:Class="App.MyTabItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:app="clr-namespace:App"
>
<TabItem.Header>
<!-- This works -->
<TextBlock Text="{Binding ElementName=Self, Path=ShortLabel, UpdateSourceTrigger=PropertyChanged}"/>
</TabItem.Header>
<TabItem.ContentTemplate>
<DataTemplate>
<!-- This binds to "Self" in the surrounding window's namespace -->
<TextBlock Text="{Binding ElementName=Self, Path=ShortLabel, UpdateSourceTrigger=PropertyChanged}"/>
这个自定义 TabItem 定义了一个 DependencyProperty "ShortLabel" 来实现某个接口。我想从 TabItem 的 DataTemplate 内部绑定到这个和其他属性,但由于奇怪的交互作用,DataTemplate 中的 TextBlock 会绑定到 TabItem 的父容器上,该父容器也被称为“Self”,但在另一个 Xaml 文件中定义。
问题:为什么绑定可以在 TabItem.Header 中正常工作,但不能在 TabItem.ContentTemplate 内部工作?我应该如何才能从 DataTemplate 内部访问到用户控件的属性?
我已经尝试过:
TemplateBinding
: 尝试绑定到TabItem
内部的ContentPresenter
。FindAncestor, AncestorType={x:Type TabItem}
: 找不到TabItem
父级。当我指定MyTabItem
类型时,这也不起作用。ElementName=Self
: 尝试在错误的范围(父容器而不是TabItem
)中绑定到具有该名称的控件。我认为这给出了一个提示,为什么这不起作用:DataTemplate没有在XAML中定义的位置创建,而是显然由父容器创建。
我想我可以替换整个ControlTemplate
来实现我想要的效果,但由于我希望保留TabItem
的默认外观和感觉,而不必维护整个ControlTemplate
,所以我非常不愿意这样做。
编辑
同时,我已经发现问题所在:如果TabControl
包含Visual
,那么它就不能有(任何)ItemsTemplate
(这包括DisplayMemberPath
)。这里有一篇MSDN论坛上的帖子解释为什么。由于这似乎是WPF的TabControl的一个根本性问题,我将关闭这个问题。感谢你们所有人的帮助!