Robbert Dam
Robbert Dam

Reputation: 4107

Passing parameters to a template

Say I have defined a button with rounded corners.

<Style x:Key="RoundButton" TargetType="Button">
    <!-- bla bla -->
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border CornerRadius="0,5,5,0" />
                <!-- bla bla -->
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

I it possible that the user of this button can specify the CornerRadius? Can I use a TemplateBinding? But where should I bind to? (to Tag?)

Upvotes: 4

Views: 2384

Answers (3)

Kent Boogaart
Kent Boogaart

Reputation: 178650

In order to use a TemplateBinding, there must be a property on the templated control (Button, in this case). Button does not have a CornerRadius or equivalent property, so your options are:

  • hard code the value in the template
  • Hijack another property (such as Tag) to store this information. This is quicker, but lacks type safety, is harder to maintain, and prevents other uses of that property.
  • Subclass Button and add the propery you need, then provide a template for that subclass. This takes a little longer but yields a much nicer experience for consumers of your control.

Upvotes: 5

Sorskoot
Sorskoot

Reputation: 10310

The button type doesn't have a property for CornerRadius, so templating this won't be possible. I think the easiest way is creating a new class which inherits from Button and add a new dependency property for the CornerRadius. Like this:

using System.Windows;
using System.Windows.Controls;

namespace WpfApplication3
{
    public class RoundedButton:Button
    {
        public CornerRadius CornerRadius
        {
            get { return (CornerRadius) GetValue(CornerRadiusProperty); }
            set { SetValue(CornerRadiusProperty, value); }
        }
        public static readonly DependencyProperty CornerRadiusProperty =
            DependencyProperty.Register("CornerRadius", typeof (CornerRadius), 
            typeof (RoundedButton), new UIPropertyMetadata());
    }
}

In xaml you can use it like:

<Local:RoundedButton 
    Style="{DynamicResource RoundButton}" 
    Width="64" Height="32" 
    Content="Hello" 
    CornerRadius="1,5,10,5" 
    Background="#FF9CFFD5" />     

A template binding to the CornerRadius will work without a problem now.

Upvotes: 1

Thomas Levesque
Thomas Levesque

Reputation: 292405

In addition to Kent's suggestions, you could also create an attached property to define the CornerRadius on the button, and bind to that property in the template

Upvotes: 6

Related Questions