Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
788 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 Reply

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).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...