定义默认布局属性

时间:2013-01-24 22:09:45

标签: wpf templates user-interface

我想在整个视图中的所有控件中设置一致的边距。我目前使用XAML:

<Window.Resources>
    <Thickness x:Key="ConsistentMargins">0,10,0,0</Thickness>
</Window.Resources>

<!-- ... -->
<!-- ... -->
<!-- ... -->

<MyControl1 Margin="{StaticResource ConsistentMargins}">
<MyControl2 Margin="{StaticResource ConsistentMargins}">
<MyControl3 Margin="{StaticResource ConsistentMargins}">

有没有办法为控件设置默认布局样式以避免上面显示的上述重复代码?

2 个答案:

答案 0 :(得分:1)

您可以使用TargetType创建自己的样式,此样式将分配给您在TargetType中指定的所有类型的对象。但在这种情况下,您创建的样式将仅应用于特定类型的对象,但不适用于派生类型。

E.g。你可以为所有按钮创建样式:

<Style TargetType="{x:Type Button}">
    <Setter Property="Margin" Value="0,10,0,0" />
</Style>

我认为从基类不应用样式是有道理的,因为我想说&#34;我的所有按钮看起来像......&#34;,但我不想说&#34;一切看起来像...&#34;

答案 1 :(得分:0)

您可以为FrameworkElement创建基本默认样式,并让其他元素类型的默认样式扩展基本样式:

<Window.Resources>
    <Style TargetType="FrameworkElement">
        <Setter Property="Margin" Value="0,10,0,0"/>
    </Style>
    <Style TargetType="TextBlock" BasedOn="{StaticResource {x:Type FrameworkElement}}"/>
    <Style TargetType="TextBox" BasedOn="{StaticResource {x:Type FrameworkElement}}"/>
    <Style TargetType="Label" BasedOn="{StaticResource {x:Type FrameworkElement}}"/>
    ...
</Window.Resources>