本文介绍了WPF:为什么我不应该在ControlTemplate中使用{TemplateBinding Margin}-Margin仅用于元素的容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

该按钮实际上具有两倍的Margin-40.实际上,我认为控件不应该使用Margin,并且Margin属性仅在安排阶段由按钮的祖先读取.然后,我研究了WPF的默认样式,发现没有一个使用Margin.

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.

这是正确的结论吗(保证金只能由容器正确地控制)?换句话说,每当我以自己的样式使用{TemplateBinding 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)?

您能指出我要解释这一点的MSDN页面吗?谢谢!

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

我想我应该在 http://msdn.microsoft.com中找到答案/en-us/library/ms745058.aspx http://msdn.microsoft.com/en-us/library/ms751709.aspx ,但我认为他们没有明确提到使用Margin属性的控件是从不 始终对其进行评估并使用它来影响布局的祖先或wpf系统...

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...

推荐答案

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

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.

这篇关于WPF:为什么我不应该在ControlTemplate中使用{TemplateBinding Margin}-Margin仅用于元素的容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 15:13