WPF:为什么我不应该在ControlTemplate中使用{TemplateBinding Margin} - Margin是否只适用于元素的容器?

Tom*_*fka 9 wpf layout margin controltemplate

我已经为Button创建了自己的ControlTemplate,如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

现在,我注意到当我将余量设置为我的按钮时,例如:

<Button 
    Style="{StaticResource LightButtonStyle}"
    Margin="20"
    >
    Hello world!
</Button>
Run Code Online (Sandbox Code Playgroud)

按钮实际上是双边距-40.我认为控件实际上应该从不使用边距,并且在安排阶段只有按钮的祖先才能读取边距属性.我已经看了WPF的默认样式,并发现没有人使用过Margin.

这是正确的结论(保证金只能由集装箱正确安排)吗?换句话说,每次我在我的风格中使用{TemplateBinding Margin}时,我会获得双倍边距?是否有一些类似属性的列表,我的控件不应该使用(因为它们仅仅用于"周围世界")?

你能指点我的MSDN页面来解释这个吗?谢谢!

编辑:

我想我应该在http://msdn.microsoft.com/en-us/library/ms745058.aspxhttp://msdn.microsoft.com/en-us/library/ms751709.aspx找到答案,但我不知道我们认为他们明确提到使用Margin属性永远不是控制者,它始终是评估它并使用它来影响布局的祖先或wpf系统......

Avi*_* P. 6

您的结论是正确的,如果您查看框架提供的默认模板,您将看到Margin模板内部绑定到Padding控件的属性.


Bry*_*son 5

边距由布局系统自动应用,在控件模板中,您应该使用Padding.

<Border x:Name="WrappingBorder" Margin="{TemplateBinding Padding}" ... />
Run Code Online (Sandbox Code Playgroud)