XAML样式中的重复

时间:2017-02-21 16:04:01

标签: xaml xaml-resources

我有xaml样式,它们具有不同的目标类型,但在其他方面是相同的。有没有办法可以减少重复并只定义一次风格?

<Style TargetType="TextBlock">            
    <Setter Property="Height" Value="{StaticResource ElementHeight}"/>
    <Setter Property="MinWidth" Value="{StaticResource ElementMinWidth}"/>
    <Setter Property="Margin" Value="{StaticResource ElementMargin}"/>
</Style>

<Style TargetType="TextBox">
    <Setter Property="Height" Value="{StaticResource ElementHeight}"/>
    <Setter Property="MinWidth" Value="{StaticResource ElementMinWidth}"/>
    <Setter Property="Margin" Value="{StaticResource ElementMargin}"/>
</Style>

<Style TargetType="ComboBox">
    <Setter Property="Height" Value="{StaticResource ElementHeight}"/>
    <Setter Property="MinWidth" Value="{StaticResource ElementMinWidth}"/>
    <Setter Property="Margin" Value="{StaticResource ElementMargin}"/>
</Style>

1 个答案:

答案 0 :(得分:2)

您可以在Style.BasedOn的帮助下使用样式继承。

首先定义基本样式:

   <Style x:Key="BaseStyle" TargetType="FrameworkElement">
        <Setter Property="Height" Value="80"/>
        <Setter Property="MinWidth" Value="80"/>
        <Setter Property="Margin" Value="80"/>
    </Style>

然后从你想要的控件中“继承”样式:

    <Style TargetType="TextBlock" BasedOn="{StaticResource BaseStyle}"/>
    <Style TargetType="TextBox" BasedOn="{StaticResource BaseStyle}"/>
    <Style TargetType="ComboBox" BasedOn="{StaticResource BaseStyle}"/>
相关问题