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

24
我希望在我放在所有窗口上的控件上设置默认的3个间距,并能够仅仅覆盖一些少数项的值。
我看到过一些方法,例如使用样式,但这需要对所有控件进行样式设置。我更喜欢可以同时应用于所有控件的方法。我也看到了MarginSetter等其他东西,但似乎它不遍历子面板。我只想在我放置在窗口上的控件上设置Margin,与可视树的边框或其他内容无关。
对我来说,这似乎是一些相当基础的东西。有任何想法吗?
提前感谢。

边框是控件。使用样式有什么问题吗?如果您使用Wpf,请查看隐式样式-可以应用于特定类型(SL5也应该有它们)。 - user572559
@Dmitry:问题在于我需要为每个由我使用的人创建的控件创建样式。考虑到所有控件都有基类,并且继承用于避免这种事情(编程时重复的东西总是错误的),这看起来不是一个好的解决方案。 - Ignacio Soler Garcia
你读了我说的话吗?使用隐式样式,它们应用于类型而不是实例级别。 - user572559
@Dmitry:我在谈论为今后创建的每种类型的控件创建样式。 - Ignacio Soler Garcia
我明白了,样式是最简单且正确的方法来实现你所寻找的东西。 - user572559
3个回答

25

我能找到的唯一解决方案是将样式应用于窗口上正在使用的每个控件(我知道这不完全是你想要的)。如果您只使用了几种不同的控件类型,那么像这样做并不太困难:

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

祝你好运...


好的,问题是Windows Form有一个默认的Margin值...而且所有的东西都需要设置一个边距。我正在寻找一个通用的解决方案来应用到我所有的应用程序中。看起来我将不得不为每个控件创建一个样式...这可能会伤害我的心情,因为我将需要永远维护这个该死的东西。 - Ignacio Soler Garcia
是的,这绝对是WPF的一个缺点。如果我找到更好的解决方案,我会在这里发布。 - Cameron Peters

21
您可以通过引用定义在资源中的“Thickness”来链接所有边距属性。我在一个项目中刚刚这样做了...
<!-- 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}" />

对我来说关键是弄清楚边距是由“厚度”定义的。如果这已经足够清晰,或者您需要我提供完整可工作的XAML示例,请告诉我。


2
你可以在按钮样式中应用边距。当你在 StackPanel wpf 中使用这种样式的按钮时,wpf 会自动应用所需的间距。 例如,在资源字典中定义或其他地方:
 <Style x:Key="myButtonStyle"  TargetType="{x:Type Button}">
<Setter Property="Margin" Value="10"/>
....
</Style>

然后在您的 StackPanel XAML 定义中:

<StackPanel>
   <Border BorderThickness="0"/>
   <Button x:Name="VertBut1" Style="{StaticResource myButtonStyle}"      Content="Button1"/>
   <Button x:Name="VertBut2" Style="{StaticResource myButtonStyle}"      Content="Button2"/>
   <Button x:Name="VertBut3" Style="{StaticResource myButtonStyle}"      Content="Button3"/>
</StackPanel>

问候
Georgi


能否将样式添加到StackPanel并使该样式向下传递到所有子元素? - BenKoshy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接