如何申请多个样式在WPF [英] How to apply multiple styles in WPF

查看:222
本文介绍了如何申请多个样式在WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WPF中,我将如何应用多个样式到 FrameworkElement的?举例来说,我已经有一个风格的控制。我也有一个单独的风格,我想给它添加不刮走的第一个。该款式有不同的TargetTypes,所以我不能只是扩展一个用等。

In WPF, how would I apply multiple styles to a FrameworkElement? For instance, I have a control which already has a style. I also have a separate style which I would like to add to it without blowing away the first one. The styles have different TargetTypes, so I can't just extend one with the other.

推荐答案

我觉得简单的答案是,你不能这样做(至少在这个版本的WPF),你正在做什么。

也就是说,对于任何特定的元件只有一个样式都可以应用。

然而,正如其他人如上所述,也许你可以使用支持算法FMP 来帮助你。看看下面的一块松动的XAML。在这里面,你会看到,我有一个设置存在的,我想两种样式应用到该元素的基类性质的基本样式。和,其中基于基本样式的第二样式,我设置另一个属性

However, as others have stated above, maybe you can use BasedOn to help you out. Check out the following piece of loose xaml. In it you will see that I have a base style that is setting a property that exists on the base class of the element that I want to apply two styles to. And, in the second style which is based on the base style, I set another property.

所以,这里的想法......是,如果你能以某种方式分开,你要设置...根据元素要上设置多个样式的继承层次的属性...你可能有一种解决方法。

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Page.Resources>
        <Style x:Key="baseStyle" TargetType="FrameworkElement">
            <Setter Property="HorizontalAlignment" Value="Left"/>
        </Style>
        <Style TargetType="Button" BasedOn="{StaticResource baseStyle}">
            <Setter Property="Content" Value="Hello World"/>
        </Style>
    </Page.Resources>
    <Grid>
        <Button Width="200" Height="50"/>
    </Grid>
</Page>


希望这有助于。


Hope this helps.

注意:

特别需要注意的一点。如果更改了的TargetType 第二风格(在第一组XAML以上),以 ButtonBase ,两种风格做没有得到应用。然而,检查了下面的XAML下面绕过这个限制。基本上,这意味着你需要给风格的关键,并使用该密钥引用它。

One thing in particular to note. If you change the TargetType in the second style (in first set of xaml above) to ButtonBase, the two Styles do not get applied. However, check out the following xaml below to get around that restriction. Basically, it means you need to give the Style a key and reference it with that key.

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Page.Resources>
        <Style x:Key="baseStyle" TargetType="FrameworkElement">
            <Setter Property="HorizontalAlignment" Value="Left"/>
        </Style>
        <Style x:Key="derivedStyle" TargetType="ButtonBase" BasedOn="{StaticResource baseStyle}">
            <Setter Property="Content" Value="Hello World"/>
        </Style>
    </Page.Resources>
    <Grid>
        <Button Width="200" Height="50" Style="{StaticResource derivedStyle}"/>
    </Grid>
</Page>

这篇关于如何申请多个样式在WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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