如果属性未作为XAML属性公开,您如何使用{StaticResource key}?

时间:2018-01-27 05:59:47

标签: .net wpf xaml uwp

例如,而不是:

<Color x:Key="MyColor">#FFF</Color>

我想要这个:

<Color x:Key="MyColor" ColorAttribute={StaticResource MyBaseColor}/>

但问题是'ColorAttribute'没有公开。

同样在<FontFamily>PathToMyFont</FontFamily>的情况下,我想指向一个基本字体,这样我每次只想更改一个资源。

2 个答案:

答案 0 :(得分:0)

我所知道的唯一方式很可能不是你想要的(但它有效)。首先采用这个新的StaticResource扩展:

public class StaticResourceColorChannelExtension : StaticResourceExtension
{
    public object Channel { get; set; }

    public StaticResourceColorChannelExtension()
    {
    }

    public StaticResourceColorChannelExtension(object resourceKey)
        : base(resourceKey)
    {
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        object value = base.ProvideValue(serviceProvider);
        string channelStr = (string)Channel;

        Color color = (Color)value;

        switch(channelStr)
        {
            case "A":
                return color.A;
            case "R":
                return color.R;
            case "G":
                return color.G;
            case "B":
                return color.B;
        }

        return (byte)0;
    }
}

在XAML中你可以这样使用它:

<Window.Resources>
    <Color x:Key="MyColor">#FFFF00FF</Color>
    <Color x:Key="MyColor2"
           A="{local:StaticResourceColorChannel MyColor,
                                                Channel=A}"
           B="{local:StaticResourceColorChannel MyColor,
                                                Channel=B}"
           G="{local:StaticResourceColorChannel MyColor,
                                                Channel=G}"
           R="{local:StaticResourceColorChannel MyColor,
                                                Channel=R}" />
    <SolidColorBrush x:Key="MyColor2Brush"
                     Color="{StaticResource MyColor2}" />
</Window.Resources>

答案 1 :(得分:0)

<Color x:Key="MyBaseColor">#FFF</Color>    
<StaticResource x:Key="MyColor" ResourceKey="MyBaseColor" />
<StaticResource x:Key="MyOtherColor" ResourceKey="MyBaseColor" />

<FontFamily x:Key="MyBaseFontFamily">...</FontFamily>
<StaticResource x:Key="MyFontFamily" ResourceKey="MyBaseFontFamily" />
<StaticResource x:Key="MyOtherFontFamily" ResourceKey="MyBaseFontFamily" />

依旧等等。