简体   繁体   English

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

[英]How to instantiate a WPF ResourceDirectory from code behind

Hi I am trying to create a ResourceDirectory from code behind the dircetory seem to bee created but it is empty (the resources specified in the xaml file is not presend. 嗨,我正在尝试从目录后面的代码创建一个ResourceDirectory,似乎是蜜蜂创建的,但是它是空的(在xaml文件中指定的资源是不存在的。

C# code: 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 code: 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>

Try the following: 请尝试以下操作:

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

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

This assumes your assembly's name is AssemblyName, and the resource dictionary's file name is DictionaryName.xaml. 这假定您的程序集的名称是AssemblyName,并且资源字典的文件名是DictionaryName.xaml。 It also assumes this file is at the project's root directory. 它还假定此文件位于项目的根目录下。 If it's within another directory, you need to fix the URI appropriately. 如果在另一个目录中,则需要适当地修复URI。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM