好的...这让我感到困惑。我有两个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正确设置,但反过来则不行),尽管两个依赖属性都设置为双向绑定!然而,使用相对源绑定而不是模板绑定时,它却能够正常工作!嗯...怎么回事?
// 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}"
那么问题出在哪里?我错过了什么吗?