如何为我的所有WPF窗口上的所有控件设置默认边距?

Ign*_*cia 18 wpf controls window margin

我想在我放在所有窗口上的所有控件上设置一个默认的3个边距,并且只能在很少的项目上覆盖这个值.

我已经看过一些像做风格的方法,但后来我需要设计一切,我更喜欢一些比所有控件都可以做到的事情.我已经看过像MarginSetter这样的其他东西,但看起来它不会遍历子面板.我只想在我放在窗口的控件上使用Margin,与视觉树的边框或其他东西无关.

看起来对我来说非常基本.有任何想法吗?

提前致谢.

Cam*_*ers 22

我能找到的唯一解决方案是将样式应用于您在窗口中使用的每个控件(我知道这不是您想要的).如果您只使用几种不同的控件类型,那么执行以下操作并不会太繁琐:

<Window x:Class="WpfApplication7.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <!-- One style for each *type* of control on the window -->
        <Style TargetType="TextBox">
            <Setter Property="Margin" Value="10"/>
        </Style>
        <Style TargetType="TextBlock">
            <Setter Property="Margin" Value="10"/>
        </Style>
    </Window.Resources>
    <StackPanel>
        <TextBox Text="TextBox"/>
        <TextBlock Text="TextBlock"/>
    </StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)

祝好运...


小智 16

您可以通过参考资源中定义的"厚度"链接所有边距属性.我刚刚在一个项目中做到了这一点......

<!-- somwhere in a resource-->
<Thickness  x:Key="CommonMargin" Left="0" Right="14" Top="6" Bottom="0" />

<!-- Inside of a Style -->
<Style TargetType="{x:Type Control}" x:Key="MyStyle">
     <Setter Property="Margin" Value="{StaticResource CommonMargin}" />
</Style>
<!-- Then call the style in a control -->
<Button Style="{StaticResource MyStyle}" />

<!-- Or directly on a Control -->
<Button Margin="{StaticResource CommonMargin}" />
Run Code Online (Sandbox Code Playgroud)

对我而言,关键在于确定边距是由"厚度"定义的.让我知道这是否足够清楚,或者你是否需要我把它放在一个完全可用的XAML示例中.