在Silverlight中使用资源字典作为主题

8

我开发了一个应用程序,允许用户在不同的主题之间切换。我通过将xaml文件作为资源包含在我的项目中,并使用以下代码来实现:

MainTheme.ThemeUri = new Uri("SilverlightApplication1;component/Themes/[ThemeName]/Theme.xaml", UriKind.Relative);

这个方法之前一直运行良好,直到我发现这些主题:http://timheuer.com/blog/archive/2010/05/17/silverlight-4-tools-released-and-new-application-templates.aspx。不同之处在于这些主题由多个文件组成。因此,我创建了一个只包含合并字典的Theme.xaml文件,以便仍然可以使用上面的代码。这是Cosmopolitan主题的Theme.xaml文件。
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="CoreStyles.xaml"/>
        <ResourceDictionary Source="SDKStyles.xaml"/>
        <ResourceDictionary Source="Styles.xaml"/>
        <ResourceDictionary Source="ToolkitStyles.xaml"/>
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

然而,当我运行以上C#代码时,我会得到以下异常:
System.Windows.Markup.XamlParseException: Failed to assign to property 'System.Windows.ResourceDictionary.Source'.

只是为了明确,当我在App.xaml中设置MergedDictionaries方法时,它确实起作用:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Themes/Cosmopolitan/Theme.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

我做错了什么?

谢谢!


在我的Theme.xaml文件中设置绝对路径也不起作用 :( - SaphuA
我曾经遇到过类似的问题,原因是在引用文件时使用了反斜杠(\)而不是正斜杠(/)。VS中的xaml解析器能够解决位置问题,但在运行时会生成错误。希望这能对其他人有所帮助。 - Steve Wranovsky
1个回答

10

当你在使用MergedDictionary时,必须像下面这样使用完全限定名称。

<ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/SilverlightApplication1;component/Themes/Cosmopolitan/Theme.xaml"/>

此外,请注意在汇编名称前不要漏掉反斜杠。换句话说,应该像这样:

Source="/SilverlightApplication1;

不像

Source="SilverlightApplication1;

希望对你有帮助


5
在汇编名称后面不需要加上“component”,正确的写法是:“/SilverlightApplication1;component/Themes/Cosmopolitan/Theme.xaml”。 - user20358
1
@Prince:组件部分是必不可少的。请考虑更新你的答案。更新后会更好。 - Avada Kedavra

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