如何参数化/重用 XAML 控件样式? [英] How to parameterize / reuse XAML control style?

查看:22
本文介绍了如何参数化/重用 XAML 控件样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为按钮定义了一种特殊样式,用于应用程序中的所有按钮.按钮的背景定义为具有两种颜色的垂直 LinearGradientBrush.如果按下按钮,则通过触发器交换两种颜色.

I have defined a special style for buttons which is used for all buttons in the application. The background of the button is defined as a vertical LinearGradientBrush with two colors. If the button is pressed down the two colors are swapped via triggers.

现在我需要一些使用不同颜色渐变的按钮,其他一切都相同.我如何重用已定义的样式?

Now I need some buttons that use different colors for the gradient, everything else being equal. How can I reuse the already defined style for that?

推荐答案

您可以在基础 Style 中将您的画笔引用为 DynamicResource 并将新画笔添加到您的派生 DynamicResource代码>样式

You could reference your brushes as DynamicResource in the base Style and add new brushses to your derived Style

基本样式 使用DynamicResource作为backgroundBrush和pressedBackgroundBrush

Base Style uses DynamicResource for backgroundBrush and pressedBackgroundBrush

<Style TargetType="Button"
        x:Key="ButtonBaseStyle">
    <Style.Resources>
        <LinearGradientBrush x:Key="backgroundBrush" StartPoint="0.5, 0" EndPoint="0.5, 1">
            <GradientStop Color="Red" Offset="0"/>
            <GradientStop Color="Green" Offset="1"/>
        </LinearGradientBrush>
        <LinearGradientBrush x:Key="pressedBackgroundBrush" StartPoint="0.5, 0" EndPoint="0.5, 1">
            <GradientStop Color="Green" Offset="0"/>
            <GradientStop Color="Red" Offset="1"/>                    
        </LinearGradientBrush>
    </Style.Resources>
    <Setter Property="Background" Value="{DynamicResource backgroundBrush}"/>
    <!-- Additional Setters.. -->
    <Style.Triggers>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="Background"
                    Value="{DynamicResource pressedBackgroundBrush}"/>
        </Trigger>
    </Style.Triggers>
</Style>

BasedOn Style 定义新的画笔,但使用相同的Style

<Style TargetType="Button"
        BasedOn="{StaticResource ButtonBaseStyle}"
        x:Key="AnotherButtonStyle">
    <Style.Resources>
        <LinearGradientBrush x:Key="backgroundBrush" StartPoint="0.5, 0" EndPoint="0.5, 1">
            <GradientStop Color="Orange" Offset="0"/>
            <GradientStop Color="Blue" Offset="1"/>
        </LinearGradientBrush>
        <LinearGradientBrush x:Key="pressedBackgroundBrush" StartPoint="0.5, 0" EndPoint="0.5, 1">
            <GradientStop Color="Blue" Offset="0"/>
            <GradientStop Color="Orange" Offset="1"/>
        </LinearGradientBrush>
    </Style.Resources>
</Style>

这篇关于如何参数化/重用 XAML 控件样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆