如何从后面的代码实例化WPF ResourceDirectory

时间:2019-02-13 13:08:27

标签: c# wpf prism-4

嗨,我正在尝试根据似乎创建的目录后面的代码创建一个ResourceDirectory,但是它是空的(xaml文件中指定的资源不存在。

C#代码:

    public static void InstallResources(IUnityContainer container)
    {
        var viewModelLocatorResources = new ViewModelLocatorResources();
        viewModelLocatorResources.InitializeComponent();
        Application.Current.Resources.MergedDictionaries.Add(viewModelLocatorResources);
        var viewModelLocator = (KViewModelLocator)Application.Current.Resources.FindName("ViewModelLocator");
        // Error viewModelLocator is null
        var viewModelResolver = (UnityViewModelResolver)viewModelLocator.Resolver;
        viewModelResolver.SetContainer(container);
    }

XAML代码:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:viewModelSupport="clr-namespace:KWPFComponents.ViewModelSupport"
                x:Class="ViewModelLocatorResources">
    <viewModelSupport:KViewModelLocator x:Key="ViewModelLocator">
        <viewModelSupport:KViewModelLocator.Resolver>
            <viewModelSupport:UnityViewModelResolver />
        </viewModelSupport:KViewModelLocator.Resolver>
    </viewModelSupport:KViewModelLocator>
</ResourceDictionary>

1 个答案:

答案 0 :(得分:0)

尝试以下操作:

var resourceDictionary = new ResourceDictionary
{
    Source = new Uri("/AssemblyName;component/DictionaryName.xaml", UriKind.Relative)
};

var viewModelLocator = (KViewModelLocator)resourceDictionary["ViewModelLocator"];

这假定您的程序集的名称为AssemblyName,而资源字典的文件名为DictionaryName.xaml。它还假定此文件位于项目的根目录下。如果它在另一个目录中,则需要适当地修复URI。