In WPF, why doesn't TemplateBinding work where Binding does?

前端 未结 2 2028
轻奢々
轻奢々 2020-11-28 11:40

Ok... this is leaving me scratching my head. I have two WPF controls--one\'s a user control and the other\'s a custom control. Let\'s call them UserFoo and CustomFoo. In

相关标签:
2条回答
  • 2020-11-28 12:16

    Found this forum post on MSDN: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/0bb3858c-30d6-4c3d-93bd-35ad0bb36bb4/

    It says this:

    A TemplateBinding is an optimized form of a Binding for template scenarios, analogous to a Binding constructed with

    {Binding RelativeSource={RelativeSource TemplatedParent}}
    

    Note from OP: Contrary to what it says in the documentation, in actuality, it should be this...

    {Binding RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}
    

    I filed a complaint against the docs, and while they did add a sentence now stating they are always one-way, the code example still doesn't list the mode, but I guess it's better than nothing.)

    The TemplateBinding transfers data from the templated parent to the property that is template bound. If you need to transfer data in the opposite direction or both ways, create a Binding with RelativeSource of TemplatedParent with the Mode property set to OneWayToSource or TwoWay.

    More in: http://msdn.microsoft.com/en-us/library/ms742882.aspx

    Looks like Mode=OneWay is one of the "Optimizations" of using a TemplateBinding

    0 讨论(0)
  • 2020-11-28 12:17

    TemplateBinding does not support two-way binding, only Binding does that. Even with your BindsTwoWayBeDefault option, it won't support two-way binding.

    More info can be found here, but to summarize:

    However, a TemplateBinding can only transfer data in one direction: from the templated parent to the element with the TemplateBinding. If you need to transfer data in the opposite direction or both ways, a Binding with RelativeSource of TemplatedParent is your only option. For example, interaction with a TextBox or Slider within a template will only change a property on the templated parent if you use a two-way Binding.

    0 讨论(0)
提交回复
热议问题