Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Why shouldn't I use {TemplateBinding Margin} in ControlTemplate - is Margin meant only for element's containers?

I have created my own ControlTemplate for Button, like this:

<Style x:Key="LightButtonStyle" TargetType="{x:Type ButtonBase}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ButtonBase}">
                <Border
                    x:Name="WrappingBorder"
                    Margin="{TemplateBinding Margin}"
                    ...
                    >
                    <ContentPresenter 
                        Content="{TemplateBinding Content}" 
                        ...
                        >
                    </ContentPresenter>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Now, I have noticed that when I set margin to my button, like:

<Button 
    Style="{StaticResource LightButtonStyle}"
    Margin="20"
    >
    Hello world!
</Button>

the button has actually double Margin - 40. I assumed that the control should, in fact, never use Margin, and that Margin property is read only by button's ancestors during arrange phase. I have looked then into WPF default styles, and found out that no one of those used Margin.

Is this the right conclusion (that Margin is in control only to be correctly arranged by containers)? In other words, every time I use {TemplateBinding Margin} in my style, I'll get double margins instead? And is there some list of similar properties that my control shouldn't use (as they are meant only for 'surrounding world' only)?

Would you point me to MSDN page that explains this? Thank you!

EDIT:

I guess I should find answers in http://msdn.microsoft.com/en-us/library/ms745058.aspx and http://msdn.microsoft.com/en-us/library/ms751709.aspx, but I don't think they mentioned explicitly that it's never the control who uses the Margin property, that it is always the ancestor or wpf system who evalues it and uses it to affect the layout...

like image 366
Tomáš Kafka Avatar asked Feb 04 '23 07:02

Tomáš Kafka


1 Answers

Your conclusion is right, if you look at the framework provided default templates you'll see that the Margin inside the template is bound to the Padding property of the control.

like image 55
Aviad P. Avatar answered Feb 06 '23 10:02

Aviad P.