【问题标题】:Setting VerticalAlignment property to all controls将 VerticalAlignment 属性设置为所有控件
【发布时间】:2011-03-23 17:11:42
【问题描述】:

我的 WPF UserControl 包含两个堆栈面板,每个面板都包含标签、文本框和单选按钮。
我想用尽可能少的代码将 VerticalAlignment 属性设置为 Center 到我的 UserControl 中的所有控件。

现在我有以下解决方案:

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

这三个解决方案需要太多代码。
有没有其他写法?
我希望为FrameworkElement 定义样式会自动为所有控件设置属性,但它不起作用。

这是我当前 XAML 的 sn-p(我省略了第二个,非常相似的堆栈面板):

<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 的评论:我真的很讨厌在代码隐藏中编写控制格式代码的想法。对于这个非常简单的用户控件,XAML 应该足够了。

Re Muad'Dib 的评论:我在用户控件中使用的控件源自FrameworkElement,所以这不是问题。

【问题讨论】:

  • 在代码隐藏中设置这个想法会像我认为的那样可怕吗?
  • 并非所有控件都继承自 FrameworkElement

标签: wpf layout styles


【解决方案1】:

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

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

【讨论】:

  • 是的,资源增加了三行,但控件的混乱程度降低了。看起来比我当前的代码更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-28
  • 1970-01-01
  • 2011-03-23
  • 2011-03-12
  • 2017-09-07
  • 1970-01-01
  • 2012-08-17
相关资源
最近更新 更多