Error when using StaticResourceExtension inside Style.Resources

前端 未结 2 1100
情歌与酒
情歌与酒 2020-12-20 08:59

I am using DynamicResource in a template, and StaticResourceExtensions as resource inside each style using that template, so that the DynamicResource is evaluated differentl

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-20 09:07

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

    It smells like you found a similar situation:

    
    
    

    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:

    
    

    I hope this can help you with your issue.

提交回复
热议问题