Noel Widmer
Noel Widmer

Reputation: 4572

WPF: Which properties are applied to the ControlTemplate

I'd like to understand which properties of an xaml Control are applied to the ControlTemplate of that Control.
F.e. If I create a Control based on the Window Class like this:
(This is very simplified — It doesn't make sense in the current state I know...)

public class BaseWindow : Window {
   public BaseWindow() { }
}

And the Template:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:shell="clr-namespace:Microsoft.Windows.Shell;assembly=Microsoft.Windows.Shell"
                    xmlns:local="clr-namespace:Arctic">



    <Style TargetType="{x:Type local:BaseWindow}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:BaseWindow}">



                    <Grid Background="Transparent">
                        <Border Background="{TemplateBinding Background}"/>
                        <ContentPresenter/>
                    </Grid>



                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

Now, when I specify a BaseWindow Control in my app the Margin Property is applied to the BaseWindow without specifying a TemplateBinding. The Background isn't, I have to declare the TemplateBinding in the Template in order to achieve that.
Can you explain to me why some properties are applied to the ControlTemplate by default and others are not?

My guess is, that the Window.xaml (Default Window Template of WPF) binds to some properties like the Margin but ignores some like Background. If that is true, then I do not understand why I can set the Background in a Window Control and it is applied to it. Seems like the Window binds to some properties and stops doing that when you derive from it…
This is probably completely wrong — I just wanted to explain my thoughts.

Upvotes: 0

Views: 90

Answers (1)

Sinatr
Sinatr

Reputation: 21999

Window class inherit FrameworkElement and all its properties including FrameworkElement.Margin. Same goes for Control.Background. Your question is why you have to do something to have Control.Background working.

Answer is simple:

  • Margin is used in layouting, its functionality is implemented/provided by FrameworkElement and it happens always, invisible for you and disregarding of ControlTemplate (because all framework elements participate in layouting and use margin).

  • Background, in turn, is provided to be use by visuals. It's up to you how to use it, because only you know how control will looks like. Control doesn't know what to do with that property.

So, you have to use TemplateBinding to bind Background to some color in your ControlTemplate, but Margin works without need to do anything in control template.

Upvotes: 0

Related Questions