Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
860 views
in Technique[技术] by (71.8m points)

wpf - What is the template binding vs binding?

I could not understand BorderThickness="{TemplateBinding BorderThickness}. Here the code:

<ControlTemplate TargetType="{x:Type wpftoolkit:DataGridCell}">
    <Border Padding="{TemplateBinding Padding}" 
            BorderBrush="{TemplateBinding BorderBrush}" 
            BorderThickness="{TemplateBinding BorderThickness}" 
            Background="{TemplateBinding Background}" 
            SnapsToDevicePixels="True">
        <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
    </Border>
</ControlTemplate>

Also please explain other types of binding.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

TemplateBinding is used for binding to the element properties within the template definition. In your example, you could have written:

 <Border Padding="{Binding Padding}" ...>

...meaning to bind the border's padding property to the padding property of... what? You'd like to say, "padding property of the control that this template is being used for." You can't give it a name because you don't know the x:Name of the control at this time (even if you did, it wouldn't work because it's in a different namescope). However, you can do this by defining a relative source

<Border Padding="{Binding Padding, RelativeSource={RelativeSource TemplatedParent}" ...>

or use TemplateBinding, which is a shortcut(*) for above

<Border Padding="{TemplateBinding Padding}" ...>

(*) In addition to being less verbose in these templating scenarios, TemplateBinding has a couple of differences compared to a regular binding:

  • It is evaluated at compile-time. (if, for example, Padding property didn't exist, you would get a compile error. But if you were to use a binding with TemplatedParent, you would only see the error at runtime.)
  • It is always a one-way binding.
  • It requires that both the source and target properties are dependency properties.
  • It has much less functionality (no StringFormat, Delay, IsAsync, etc.. see the properties of Binding vs TemplateBindingExtention).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...