wpf - WPF TemplateBinding vs RelativeSource TemplatedParent

This is a post that summarizes the dicussion on WPF TemplateBinding vs RelativeSource TemplatedParent; This is a quote from the original site, however, I may add some verifcation code to attest/affirm/adjure it.

 

 

The orignal quesetion is what is the differences between 

 

 

<ControlTemplate TargetType="{x:Type Button}">
   <Border BorderBrush="{TemplateBinding Property=Background}">
      <ContentPresenter />
   </Border>
</ControlTemplate>

 

and 

 

 

<ControlTemplate TargetType="{x:Type Button}">
   <Border BorderBrush="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background}">
      <ContentPresenter />
   </Border>
</ControlTemplate>

 

one of the best answers have something like this:

 

Grant BlahaErath 写道
TemplateBinding is not quite the same thing. MSDN docs are often written by people that have to quiz monosyllabic SDEs about software features, so the nuances are not quite right.

TemplateBindings are evaluated at compile time against the type specified in the control template. This allows for much faster instantiation of compiled templates. Just fumble the name in a templatebinding and you'll see that the compiler will flag it.

The binding markup is resolved at runtime. While slower to execute, the binding will resolve property names that are not visible on the type declared by the template. By slower, I'll point out that its kind of relative since the binding operation takes very little of the application's cpu. If you were blasting control templates around at high speed you might notice it.

As a matter of practice use the TemplateBinding when you can but don't fear the Binding.
 

and another answers is that 

 

Pual Fischer 写道
TemplateBinding - More limiting than using regular Binding

More efficient than a Binding but it has less functionality
Only works inside a ControlTemplate's visual tree
Doesn't work with properties on Freezables
Doesn't work within a ControlTemplate's Trigger
Provides a shortcut in setting properties(not as verbose),e.g. {TemplateBinding targetProperty}
Regular Binding - Does not have above limitations of TemplateBinding

Respects Parent Properties
Resets Target Values to clear out any explicitly set values
Example: <Ellipse Fill="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Background}"/>
 

你可能感兴趣的:(WPF)