gpt4 book ai didi

wpf - 为所有控件设置 VerticalAlignment 属性

转载 作者:行者123 更新时间:2023-12-03 18:31:09 26 4
gpt4 key购买 nike

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

现在我有以下解决方案:

  • 蛮力 - 放 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>

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

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

    最佳答案

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

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

    关于wpf - 为所有控件设置 VerticalAlignment 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3379587/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com