How to instantiate a WPF ResourceDirectory from code behind

85 Views Asked by At

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.

C# code:

    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:

<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

There are 1 best solutions below

0
redcurry On

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. 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.