代码之家  ›  专栏  ›  技术社区  ›  zendar

将VerticalAlignment属性设置为所有控件

  •  6
  • zendar  · 技术社区  · 15 年前


    我想设置 VerticalAlignment Center 以尽可能少的代码访问UserControl中的所有控件。

    现在我有以下解决方案:

    • VerticalAlignment="Center" 在每个控件中
    • 定义一种样式 FrameworkElement
    • 为用户控件上的每种类型的控件定义样式(这需要3个样式定义,但会自动将样式应用于控件)

    这三种解决方案需要太多的代码。
    还有别的方法写这个吗?
    我希望这种风格 框架元件 会自动将属性设置为所有控件,但它不起作用。

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

    编辑:
    Re Will的评论:我真的很讨厌用codebehind编写控件格式化代码。XAML对于这个非常简单的用户控件来说应该足够了。

    Re Muad'Dib的评论:我在用户控件中使用的控件是从

    1 回复  |  直到 14 年前
        1
  •  11
  •   Metro Smurf    15 年前

    不久前我也遇到了同样的难题。不确定这是否是“最佳”方式,但通过定义基本样式,然后为继承自基本样式的页面上的每个控件创建单独的样式,管理起来非常简单:

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