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

是否可以同时将WPF样式应用于不同的类型?

  •  4
  • Meh  · 技术社区  · 15 年前

    我想创建一个可以应用于不同控件类型的样式。像这样的:

    <ToolBar>
        <ToolBar.Resources>
            <Style TargetType="Control">
                <Setter Property="Margin" Value="1"/>
                <Setter Property="Padding" Value="0"/>
            </Style>
        </ToolBar.Resources>
    
        <ComboBox .../>
        <Button .../>
    </ToolBar>
    

    它应该适用于 ComboBox 以及 Button . 但它不像我在这里写的那样工作。

    这有可能吗?只针对这些类的一个祖先,比如 Control ? 如果不是,那么对一堆控件应用公共设置的最佳方法是什么?

    2 回复  |  直到 15 年前
        1
  •  9
  •   Community Mohan Dere    9 年前

    更新

    见 this 讨论有趣的方法

    见 this 问题

    您创建的样式仅针对控件,而不是从控件派生的元素。如果不设置x:Key,则将x:Key隐式设置为TargetType,因此如果TargetType=“Control”,则x:Key=“Control”。我不认为有任何直接的方法可以做到这一点。

    你的选择是

    <Style x:Key="ControlBaseStyle" TargetType="Control">  
        <Setter Property="Margin" Value="1"/>  
        <Setter Property="Padding" Value="0"/>  
    </Style>  
    

    例如,以所有按钮和组合框为目标

    <Style TargetType="{x:Type Button}" BasedOn="{StaticResource ControlBaseStyle}"/> 
    <Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource ControlBaseStyle}"/> 
    

    或者直接在控件上使用样式

    <Button Style="{StaticResource ControlBaseStyle}" ...>
    <ComboBox Style="{StaticResource ControlBaseStyle}" ...>
    
        2
  •  0
  •   Jason    15 年前

    我不认为样式支持传统编程形式的继承。似乎你最好的选择就是按照梅勒克在第一个例子中的建议去做。这将强制每个控件类型具有相同的基样式,但仍允许您根据需要扩展每个类型的样式。

    推荐文章