如何继承 XAML 样式并覆盖子元素的属性? [英] How to inherit XAML style and override property of child element?

查看:27
本文介绍了如何继承 XAML 样式并覆盖子元素的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们刚刚开始使用 XAML,但仍在与基本问题作斗争:来自 CSS,我们想用自定义控件模板定义一个通用按钮样式,然后让第二个样式使用basedon"继承第一个样式的所有内容.然后第二个样式应该覆盖诸如前景色"之类的属性(有效)还有我们自定义模板中子元素的属性,例如包含的边框元素等的背景颜色"(这不起作用).

we just got started with XAML and are still fighting with basic issues: Coming from CSS we'd like to define a generic button style with custom control template and then have a second style inherit everything from the first style using "basedon. This second style should then override properties such e.g. "foreground color" (which works) but also properties of child elements within our custom template such as the "background color" of e.g. an included border element etc. (which doesn't work).

处理此类事情的一般方法是什么?级联样式能走多远?

What's the general approach to go about things like this? How far can we go with cascading styles?

干杯!

推荐答案

您可以使用没有键引用的继承样式:

You can use an inherited style with no key reference:

<Grid>
    <Grid.Resources>
        <!-- Definition of default appearance of a button -->
        <Style TargetType="Button" x:Key="Default">
            <Setter Property="Background" Value="Red"></Setter>
            <Setter Property="FontFamily" Value="Segoe Black" />
            <Setter Property="HorizontalAlignment" Value="Center" />
            <Setter Property="FontSize" Value="32pt" />
            <Setter Property="Foreground" Value="#777777" />
        </Style>
        <!-- Define general style that based is base on the default style of the button without a key reference-->
        <Style TargetType="Button" BasedOn="{StaticResource Default}"/>

        <!-- In sub style override the properties you need -->
        <Style BasedOn="{StaticResource Default}" TargetType="Button" x:Key="SubButton" >
            <Setter Property="FontSize" Value="8pt" />
        </Style>

    </Grid.Resources>

    <Button Content="Main" Height="51" HorizontalAlignment="Left" Margin="154,72,0,0" Name="button1" VerticalAlignment="Top" Width="141" />
    <Button Content="Sub" Style="{StaticResource SubButton}" Height="51" HorizontalAlignment="Left" Margin="154,162,0,0" Name="button2" VerticalAlignment="Top" Width="141" />
</Grid>

这篇关于如何继承 XAML 样式并覆盖子元素的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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