将VerticalAlignment属性设置为所有控件

7
我的WPF用户控件包含两个堆栈面板,每个面板都包含标签、文本框和单选按钮。
我想尽可能少地使用代码将VerticalAlignment属性设置为Center到我的用户控件中的所有控件中。
目前我有以下解决方案:
  • 蛮力法——在每个控件中放置VerticalAlignment="Center"
  • FrameworkElement定义一个样式并直接应用它
  • 为用户控件上每种类型的控件定义样式(这需要3个样式定义,但会自动将样式应用于控件)
这三种解决方案需要太多的代码。
还有其他方法可以编写吗?
我希望为FrameworkElement定义样式会自动将属性设置到所有控件上,但实际情况并非如此。
这是我当前XAML的片段(我省略了第二个非常相似的堆栈面板):
<UserControl.Resources>
    <Style x:Key="BaseStyle" TargetType="FrameworkElement">
        <Setter Property="VerticalAlignment" Value="Center" />
    </Style>
</UserControl.Resources>
<Grid>
    <StackPanel Orientation="Horizontal">
        <TextBlock Style="{StaticResource BaseStyle}" Text="Value:" />
        <RadioButton Style="{StaticResource BaseStyle}">Standard</RadioButton>
        <RadioButton Style="{StaticResource BaseStyle}">Other</RadioButton>
        <TextBox Style="{StaticResource BaseStyle}" Width="40"/>
    </StackPanel>
</Grid>

编辑:
关于Will的评论:我真的很讨厌在代码后端编写控件格式代码。对于这个非常简单的用户控件,XAML应该足够了。

关于Muad'Dib的评论:我在我的用户控件中使用的控件都派生自FrameworkElement,所以这不是一个问题。


将这个设置放在代码后端中,会像我想象的那样糟糕吗? - Will A
并非所有的控件都继承自FrameworkElement。 - Muad'Dib
1个回答

11

我曾经也遇到过同样的难题。不确定这是否是最好的方法,但通过定义基本样式,然后为页面上的每个控件创建继承自基本样式的单独样式来管理它是足够容易的:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Width="500" Height="300" Background="OrangeRed">

<Page.Resources>
  <Style TargetType="FrameworkElement" x:Key="BaseStyle">
    <Setter Property="VerticalAlignment" Value="Center" />
    <Setter Property="Margin" Value="0,0,5,0" />
  </Style>

  <Style TargetType="TextBlock" BasedOn="{StaticResource BaseStyle}" />
  <Style TargetType="RadioButton" BasedOn="{StaticResource BaseStyle}" />
  <Style TargetType="TextBox" BasedOn="{StaticResource BaseStyle}" />
</Page.Resources>

 <Grid>
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="Value:" />
        <RadioButton>Standard</RadioButton>
        <RadioButton>Other</RadioButton>
        <TextBox Width="75"/>
    </StackPanel>
</Grid>

</Page>

是的,在资源中多了三行,但控件不那么混乱。看起来比我的当前代码更好。 - zendar

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