控件模板或数据模板中的自定义资源字典

7
编辑:此问题也会在使用标准的.NET ResourceDictionary时发生,并且似乎是在控件或数据模板中使用资源字典时出现的问题。 我有一个自定义的资源字典,遵循共享资源实例的常用方法。 http://softnotes.wordpress.com/2011/04/05/shared-resourcedictionary-for-silverlight/ http://www.wpftutorial.net/MergedDictionaryPerformance.html
public class SharedResourceDictionary : ResourceDictionary
{
    static readonly Dictionary<Uri, WeakReference<ResourceDictionary>> SharedDictionaries = new Dictionary<Uri, WeakReference<ResourceDictionary>>();

    Uri _sourceUri;

    public new Uri Source
    {
        get
        {
            // Behave like standard resource dictionary for IDE...
            if (VisualStudio.IsInDesignMode)
                return base.Source;

            return this._sourceUri;
        }
        set
        {
            // Behave like standard resource dictionary for IDE...
            if (VisualStudio.IsInDesignMode)
            {
                base.Source = value;
                return;
            }

            this._sourceUri = value;

            WeakReference<ResourceDictionary> cached;
            if (SharedDictionaries.TryGetValue(value, out cached))
            {
                ResourceDictionary rd;
                if (cached.TryGetTarget(out rd))
                {
                    this.MergedDictionaries.Add(rd);
                    return;
                }
            }

            base.Source = value;
            SharedDictionaries[value] = new WeakReference<ResourceDictionary>(this);
        }
    }
}

它的功能很好,但每当它在ControlTemplate或DataTemplate内的Resources元素中被引用时,就会显示出错误(这些错误不会影响构建,构建仍然成功)。

标准ResourceDictionary中包含共享资源字典的情况下,会显示以下错误信息:

Unable to cast object of type 'Microsoft.Expression.Markup.DocumentModel.DocumentCompositeNode' to type 'System.Windows.ResourceDictionary'

示例XAML:

<DataTemplate DataType="{x:Type vm:MyViewModel}">
    <DockPanel Style="{DynamicResource MainDockPanel}">
        <DockPanel.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <p:SharedResourceDictionary Source="/MyAssembly;component/MyResources.xaml" />
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </DockPanel.Resources>
    </DockPanel>
</DataTemplate>

有人有什么想法可以消除这个麻烦的错误吗?
谢谢。

常见的方法?你有没有任何关于这种技术的更广泛讨论的链接? - Kent Boogaart
这里有一个……我稍后会找到更多时间挖掘。http://softnotes.wordpress.com/2011/04/05/shared-resourcedictionary-for-silverlight/ - Stephen Drew
http://www.wpftutorial.net/MergedDictionaryPerformance.html - Stephen Drew
我在桌面应用程序(.NET 3.5SP1和4.0)中使用类似的实现方式,并且它在运行时正常工作。为了避免在VS设计器中出现错误,我使用#if !DEBUG指令来排除SharedResourceDictionary类中的代码。 - Lubo
嗨"user1835941" :) 你排除了类的全部内容吗?我认为我的VisualStudio.IsInDesignMode可能会做类似的事情,并且在调试运行时看到类的好处会很不错。 - Stephen Drew
相同的错误也会出现在.NET资源字典中,因此它与自定义资源字典无关... - Stephen Drew
1个回答

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接