Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Custom Control TemplateBinding

How do i define a TemplateBinding for my custom control?

like image 689
Peter Avatar asked Apr 20 '10 17:04

Peter


People also ask

What is TemplateBinding?

A TemplateBinding is an optimized form of a Binding for template scenarios, analogous to a Binding constructed with {Binding RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay} . A TemplateBinding is always a one-way binding, even if properties involved default to two-way binding.

What is the difference between user control and custom control in WPF?

A customControl can be styled and templated and best suited for a situation when you are building a Control Library. On the contrary, a UserControl gives you an easy way to define reusable chunk of XAML which can be reused widely in your application and when you don't need to use it as a Control Library .

What is a ControlTemplate?

The ControlTemplate specifies the appearance of a Control. If a Control does not have a ControlTemplate, the Control will not appear in your application. The control author defines the default control template and the application author can override the ControlTemplate to redefine the visual tree of the control.


2 Answers

a little somthing like this..... (btw, this xaml is WPF, not silverlight--which is slightly different)

   <style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="Green">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid Background={TemplateBinding Background}
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </style>

now, once you apply this style to an object, whenever you set the background of that object, the template will use the Background property (this is a property on the button control) and will be defaulted to what you set in the style (in this case, green)

If you want to use a property that does not exsist on the object of your style, you have to derive your own control and add the property as either a DependencyProperty or use the INotifyPropertyChanged interface. Here is a decent explanation for you.

like image 99
Muad'Dib Avatar answered Oct 12 '22 07:10

Muad'Dib


Need a bit more information on what you are trying to do. Setting up a TemplateBinding can be done with the following XAML:

{TemplateBinding YourProperty} or

{Binding RelativeSource={RelativeSource TemplatedParent}, Path=YourProperty}

like image 43
Charlie Avatar answered Oct 12 '22 07:10

Charlie