【问题标题】:WPF StackPanel.Resources setter on more than one control type?WPF StackPanel.Resources 设置器在多个控件类型上?
【发布时间】:2011-06-28 10:20:58
【问题描述】:

我想使用 setter 设置堆栈面板中所有元素的默认边距,不仅是按钮,还有文本框和标签。

    <StackPanel>
        <StackPanel.Resources>
            <Style TargetType="{x:Type Button}">
                <Setter Property="Margin" Value="0,10,0,0"/>
            </Style>
        </StackPanel.Resources>
        ...

当我尝试将上面的 Button 更改为 ControlFrameworkElement(每个元素的派生类型)时,它不起作用。

如何解决这个问题,而不必在 TargetType 上指定 2 个不同的 Style 具有相同内容但 x:Types 的元素?

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    您可以通过 Style 的 BasedOn 属性进行继承:

            <StackPanel.Resources>
                <Style x:Key="BaseStyle" TargetType="{x:Type FrameworkElement}">
                    <Setter Property="Margin" Value="0,10,0,0"/>
                </Style>
    
                <Style TargetType="{x:Type Label}" BasedOn="{StaticResource BaseStyle}" />
                <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource BaseStyle}" />
                <Style TargetType="{x:Type Button}" BasedOn="{StaticResource BaseStyle}" />
    
            </StackPanel.Resources>
    

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 2012-03-14
      • 2011-02-12
      • 2023-04-01
      • 1970-01-01
      • 2011-01-22
      • 2010-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多