如果属性未公开为 XAML 属性,如何使用 {静态资源键}



例如,代替这个:

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

我想要这个:

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

但问题是"颜色属性"没有暴露。

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

<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" />
等等

等等。

我知道的唯一方法很可能不是你喜欢的(但它有效(。首先采用这个新的静态资源扩展:

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>

最新更新