从类库中的应用程序合并字典资源

时间:2014-10-31 10:35:05

标签: c# xaml windows-store-apps windows-phone-8.1

我有一个Windows Phone 8.1解决方案,它有一个标准应用程序项目和一个类库项目。我的想法是,我可以以某种方式StaticResources向下执行ClassLibrary,以便它可以覆盖现有的ClassLibrary。我给你举个例子: 在我的ClassLibrary中,我有一个ClassLibraryDictionary.xaml,代码如下:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ClassLibraryTest">

    <SolidColorBrush x:Key="MyButtonColor" Color="#FF0000FF" />

</ResourceDictionary>

我的想法是,在我的MainApplication中,我可以使用具有相同StaticResource密钥的Dictionary.xaml,并将其传递给我的ClassLibrary,以便它可以覆盖默认属性,如:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MainApplicationTest">

    <SolidColorBrush x:Key="MyButtonColor" Color="#00FF00FF" />

</ResourceDictionary>

并将其传递给代码:

var mainAppDictionary = new ResourceDictionary();
mainAppDictionary.Source = new Uri("/using:MainApplicationTest;component/MainApplicationDictionary.xaml", UriKind.RelativeOrAbsolute);
classLibraryTest.SetResourceDictionary(mainAppDictionary);

这里的问题是我似乎无法在我的ClassLibrary中使用ResourceDictionary实例,我甚至不确定这是最好的方法。
那么,我怎么能解决这个问题呢?

1 个答案:

答案 0 :(得分:0)

我发现了这个怎么做,实际上很简单。我使用的路径不是正确的路径,所以总结一下,XAML中的解决方案,如果你在App.xaml(在MainApp中)这样做,那就是这样:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="ms-appx://Common/yourclasslibraryname/ClassLibraryDictionary.xaml"></ResourceDictionary>
            <ResourceDictionary Source="/Dictionary1.xaml"></ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

如果您想直接在ClassLibrary中的代码中设置它,您可以这样做:
MainApp.xaml.cs

myClassLibrary.MergeAllDictionaries(App.Current.Resources);

ClassLibrary

public void MergeAllDictionaries(ResourceDictionary appDictionary) {
    // First copy all keys from MainApp to a new Dictionary
    ResourceDictionary mainDictionary = new ResourceDictionary();
    foreach(var keys in appDictionary.MergedDictionaries) {
        foreach(var keys1 in keys) {
            mainDictionary.Add(keys1.Key, keys1.Value);
        }
    }

    // Then clear all
    appDictionary.Clear();

    // Get the ClassLibrary dictionary
    ResourceDictionary classLibraryDictionary = new ResourceDictionary();
    classLibraryDictionary.Source = new Uri("ms-appx://Common/yourclasslibraryname/ClassLibraryDictionary.xaml", UriKind.RelativeOrAbsolute);

    // First add the ClassLibrary keys and values
    appDictionary.MergedDictionaries.Add(classLibraryDictionary);
    // Then add the old values, so that they overwrite the ClassLibrary ones
    appDictionary.MergedDictionaries.Add(mainDictionary);
}