好吧...这让我摸不着头脑。我有两个 WPF 控件——一个是用户控件,另一个是自定义控件。我们称它们为 UserFoo 和 CustomFoo。在 CustomFoo 的控制模板中,我使用了一个 UserFoo 实例,它是一个命名部分,因此我可以在应用模板后访问它。这很好用。
现在 UserFoo 和 CustomFoo 都Text
定义了一个属性(独立地,即不是使用 AddOwner 的共享 DP。不要问...),它们都是这样声明的...
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(string),
typeof(UserFoo), // The other is CustomFoo
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
null,
null,
true,
UpdateSourceTrigger.PropertyChanged
)
);
请特别注意,模式设置为 TwoWay,UpdateSourceTrigger 设置为 PropertyChanged,同样适用于两者。
因此,在 CustomFoo 的样式模板中,我想将 CustomFoo 的 Text 属性作为源绑定到内部 UserFoo 的 Text 属性。通常,这很容易。您只需将 UserFoo 的 text 属性设置为“{TemplateBinding Text}”,但由于某种原因,它只是一种方式(即 UserFoo 是从 CustomFoo 正确设置的,但不是相反),即使再次将两个 DP 设置为双向!但是,当使用相对源绑定而不是模板绑定时,效果很好!嗯……什么??
// This one works
Text="{Binding Text, RelativeSource={RelativeSource AncestorType={local:CustomFoo}}, Mode=TwoWay}"
// As does this too...
Text="{Binding Text, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"
// But not this one!
Text="{TemplateBinding Text}"
那么给了什么?我错过了什么?