Flip Booth
Flip Booth

Reputation: 271

WPF Optional TemplateBinding Property

Basically what I want to do is have FontSize to be optional, which means there should be a default value. Please assist.

<ControlTemplate x:Key="MyTemplate" TargetType="{x:Type Control}">
    <TextBlock 
           HorizontalAlignment="Left"
           VerticalAlignment="Center"
           MaxWidth="136"
           MaxHeight="55"
           FontSize="{TemplateBinding FontSize}"
           TextWrapping="Wrap"
           />
</ControlTemplate>

Upvotes: 0

Views: 593

Answers (1)

McGarnagle
McGarnagle

Reputation: 102793

have FontSize to be optional, which means there should be a default value

This seems like a misunderstanding of what a TemplateBinding is. TemplateBinding is a special kind of binding used inside control templates, where the source is a dependency property in the control that the template targets. Now, dependency properties can have default values -- but that is set in the definition:

public static readonly DependencyProperty SomethingProperty = DependencyProperty.Register(
    "Something", 
    typeof(double), 
    typeof(SomethingControl), 
    new FrameworkPropertyMetadata(1.0));

                                   ^ default value

In the case of the OP, the Control class owns the FontSize DP, so you can't set its default in this way. So the question becomes, what are you trying to do? A couple of options:

  1. Instead of using ControlTemplate, use a Style, and set the FontSize to your desired default. (You can also have the Style apply your ControlTemplate.)
  2. Create your own derived control, with its own "FontSize" dependency property, with the desired default applied as above.
  3. Set FontSize on your application's root control -- that will effectively set a default font size throughout your application.

It's hard to say which approach fits for your specific case, without knowing more context.

Upvotes: 1

Related Questions