char m
char m

Reputation: 8336

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

Among others I been trying:

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

-> The URI prefix is not recognized.

and

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

-> The URI prefix is not recognized.

In project folder version/src/myexename there is Locales folder and the en-US.xaml-file in it. The exe is built in version/run so I also tried:

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

-> The URI prefix is not recognized.

Upvotes: 1

Views: 2536

Answers (1)

kirotab
kirotab

Reputation: 1306

Edit 2 Initializing resource dictionary from code

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

Where WpfApplication is the name of the assembly and Dictionary1 is the name of the res file (it's located directly in the project directory in this case).

And this is 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>

Original Answer

Any reason that you want to do it in code and not in xaml ?

Here's an example from WinRT app but

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

Edit -> Usage

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

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

Upvotes: 1

Related Questions