1

有没有办法创建 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 文件

4

3 回答 3

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);
于 2012-09-14T18:33:27.117 回答
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>
于 2012-09-14T18:37:53.580 回答
0

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

于 2012-09-14T18:25:35.293 回答