如何在 WPF 应用程序主方法中从同一项目中的 xaml 文件创建 ResourceDictionary?

how to create ResourceDictionary from a xaml file in same project in WPF-application main method?

其中我一直在尝试:

ResourceDictionary localRes = new ResourceDictionary
{
    Source = new Uri("myexename;component/Locales/en-US.xaml", UriKind.RelativeOrAbsolute)
};

-> 无法识别 URI 前缀。

ResourceDictionary localRes = new ResourceDictionary
{
    Source = new Uri("/Locales/en-US.xaml", UriKind.Relative)
};

-> 无法识别 URI 前缀。

在项目文件夹 version/src/myexename 中有 Locales 文件夹和其中的 en-US.xaml- 文件。 exe 内置于 version/run 所以我也尝试过:

ResourceDictionary localRes = new ResourceDictionary
{
    Source = new Uri("../src/myexename/Locales/en-US.xaml", UriKind.Relative)
};

-> 无法识别 URI 前缀。

编辑 2 从代码初始化资源字典

var res = Application.LoadComponent(
    new Uri("/WpfApplication;component/Dictionary1.xaml", UriKind.RelativeOrAbsolute))
    as ResourceDictionary;
var testVariable = res["TestString"];

其中 WpfApplication 是程序集的名称,Dictionary1 是 res 文件的名称(在本例中它直接位于项目目录中)。

这是Dictionary1.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:clr="clr-namespace:System;assembly=mscorlib"
                xmlns:local="clr-namespace:WpfApplication">
    <clr:String x:Key="TestString">Test</clr:String>
</ResourceDictionary>

原答案

您想在代码中而不是在 xaml 中执行此操作的任何原因?

这是来自 WinRT 应用程序的示例,但是

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <!-- Styles that define common aspects of the platform look and feel
                 Required by Visual Studio project and item templates -->
            <ResourceDictionary Source="Common/StandardStyles.xaml" />
            <!-- App specific styles -->
            <ResourceDictionary Source="Assets/SomeStyles.xaml" />
            <ResourceDictionary Source="Assets/SomeMoreStyles.xaml" />
        </ResourceDictionary.MergedDictionaries>

        <vm:ViewModelLocator x:Key="Locator" />
        <!-- Converters -->
        <converters:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" />
        <converters:NullToVisibilityConverter x:Key="NullToVisibilityConverter" />
    </ResourceDictionary>
</Application.Resources>

编辑 -> 使用

var resourceDictionary = 
    Application.Current.Resources.MergedDictionaries.FirstOrDefault(x=>x.ContainsKey(key));

if(resourceDictionary != null)
{
    var someVariable = resourceDictionary[key] as VariableType;
}