ResourceDictionary定位器

时间:2012-09-14 18:04:28

标签: wpf mvvm

有没有办法创建ResourceDictionary定位器。 现在我有xaml:

 <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="../../Resources/StringResources.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>

后面的代码设置了基于currentculture的词典列表

我想要

 <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <Locator "StringResources"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>

或类似的东西,这样我就不必修改每个v.xaml.cs文件

3 个答案:

答案 0 :(得分:2)

您可以创建自己的ResourceDictionary:

public class ResourceDictionaryLocator : ResourceDictionary
{
    public ResourceDictionaryLocator()
    {
        switch (CurrentLocalization)
        {
            case "English":
                base.Source = new Uri("pack://application:,,,/Languages/English.xaml");
                break;

            case "French":
                base.Source = new Uri("pack://application:,,,/Languages/French.xaml");
                break;
        }
    }
}

然后像这样消费:

<Application x:Class="TestingWPF.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:TestingWPF"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <local:ResourceDictionaryLocator />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

然而,通常不会这样做。您可以在运行时加载不同的资源字典。如下所示:

Application.Current.Resources.MergedDictionaries.Clear();
Application.Current.Resources.MergedDictionaries.Add(dictionary);

答案 1 :(得分:2)

您可以创建一个MarkupExtension来返回所请求的ResourceDictionary:

public class ResourceDictionaryLocator : MarkupExtension
{
    public string DictionaryName { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        // Logic to return the wanted ResourceDictionary
        if (DictionaryName == "...")
        {
        }

        return null;
    }
}

然后在xaml中使用它:

<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
        <local:ResourceDictionaryLocator DictionaryName="StringResources" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

答案 2 :(得分:0)

我真的不知道这是否可行,但你想让你的应用程序成为'可本地化'吗? Baybe这篇文章可能对您有所帮助:http://www.codeproject.com/KB/WPF/WPF_Resx_Localization/