Error when using StaticResourceExtension inside Style.Resources

早过忘川 提交于 2019-11-29 13:03:45
Il Vic

As far as I know StaticResourceExtension does not work properly in some situations.

It smells like you found a similar situation:

<SolidColorBrush x:Key="RedBrush" Color="Red" />
<Style TargetType="TextBox" x:Key="Test">
    <Style.Resources>
        <StaticResourceExtension x:Key="NewRedBrushKey" ResourceKey="RedBrush" />
    </Style.Resources>
</Style>

Using the Test style in your Window is enough to reproduce your issue.

So my suggestion is to use your own extension:

public class ResourceFinder : System.Windows.Markup.MarkupExtension
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        FrameworkElement frameworkElement;
        IDictionary dictionary;
        IRootObjectProvider rootObjectProvider = (IRootObjectProvider)
            serviceProvider.GetService(typeof(IRootObjectProvider));

        if (rootObjectProvider != null) 
        {
            dictionary = rootObjectProvider.RootObject as IDictionary;

            if (dictionary != null)
            {
                return dictionary[ResourceKey];
            }
            else
            {
                frameworkElement = rootObjectProvider.RootObject as FrameworkElement;
                if (frameworkElement != null)
                {
                    return frameworkElement.TryFindResource(ResourceKey);
                }
            }

        }

        return null;
    }


    public object ResourceKey
    {
        get;
        set;
    }
}

Then your style will become:

<Style 
    x:Key="BotãoNavegaçãoBase" 
    TargetType="{x:Type ButtonBase}" 
    BasedOn="{StaticResource BotãoGeometria}">
    <Style.Resources>
        <local:ResourceFinder x:Key="PathShadow" ResourceKey="Sombra" />
    </Style.Resources>
</Style>

I hope this can help you with your issue.

Pretty sure this is a BAML compilation related bug. The code will work if compiled dynamically at run time using XamlReader.Parse. This could be used as a workaround as well, i suppose.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!