何时在 WPF 中使用 TemplateBinding 和 TemplatedParent
我对 TemplateBinding 和 TemplatedParent 感到困惑。我也浏览过这个链接 ?
但我的疑问是何时使用 TemplateBinding 和 TemplatedParent
提前致谢。
I have a confusion over TemplateBinding and TemplatedParent. I have gone through this link also
WPF TemplateBinding vs RelativeSource TemplatedParent
But my doubt is when to use TemplateBinding and TemplatedParent?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
{TemplateBinding X}
只是编写{Binding X,relativeSource={RelativeSource TemplatedParent}}
的快捷方式。尽管
TemplateBinding
是在编译时评估的,而RelativeSource TemplatedParent
是在运行时评估的,但它们的评估结果是相同的。因为它是在编译时评估的,所以
TemplateBinding
的评估速度要快一些,但如果它认为绑定属性不存在,则会抛出错误。如果您知道该属性存在,但编译器不知道它,那么您可以使用RelativeSource TemplatedParent,因为它是在运行时而不是编译时评估的。总而言之,请使用
TemplateBinding
,除非它给出错误并且您知道该属性存在。然后使用RelativeSource TemplatedParent
您链接的问题的接受答案包含关于两者之间的差异
{TemplateBinding X}
is simply a shortcut way of writing the{Binding X, RelativeSource={RelativeSource TemplatedParent}}
.They evaluate to the same thing, although
TemplateBinding
is evaluated at compile-time whileRelativeSource TemplatedParent
is evaluated at run-time.Because it is evaluated at compile-time,
TemplateBinding
is a bit faster to evaluate however it will throw errors if it doesn't think the bound property exists. If you know the property exists but the compiler doesn't know about it, then you useRelativeSource TemplatedParent
since it is evaluated at run-time instead of compile-time.To summarize, use
TemplateBinding
unless it gives you an error and you know the property exists. Then useRelativeSource TemplatedParent
The accepted answer to the question you linked contains a pretty good summary on the differences between the two