tatulea
tatulea

Reputation: 13

How to dynamically add ResourceDictionary to MergedDictionaries in WPF app

I have the next WPF part of code:

<Page.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Languages/English.xaml"/>
            <ResourceDictionary Source="Languages/Romana.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Page.Resources>

How can I select from code one of those ResourceDictionarys?

EDIT:

<Page.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Languages/English.xaml"/>
            <ResourceDictionary Source="Languages/Romana.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Page.Resources>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <ScrollViewer HorizontalScrollMode="Auto" HorizontalScrollBarVisibility="Hidden" VerticalScrollMode="Disabled" VerticalScrollBarVisibility="Hidden"  BorderThickness="0,3,0,3" BorderBrush="Aqua">
        <StackPanel Orientation="Horizontal">
            <AppBarToggleButton x:Name="Connect_toggle" Label="{StaticResource connect}" HorizontalAlignment="Stretch" Icon="Accept" VerticalAlignment="Stretch" d:LayoutOverrides="Width" Click="Connect_toggle_Click"/>
            <AppBarToggleButton x:Name="Options_toggle" Label="{StaticResource options}" HorizontalAlignment="Stretch" Icon="Accept" VerticalAlignment="Stretch" d:LayoutOverrides="Width" Click="Options_toggle_Click"/>
        </StackPanel>
    </ScrollViewer>

I did not specify that I am using Windows Universal (VS2015).

Upvotes: 1

Views: 5401

Answers (1)

Alexander Bell
Alexander Bell

Reputation: 7918

You can dynamically select the ResourceDictionary file and add it to MergedDictionaries using C# code-behind like shown in the following code snippet:

    // prefix to the relative Uri for resource (xaml file)
    string _prefix = String.Concat(typeof(App).Namespace, ";component/");

    // clear all ResourceDictionaries
    this.Resources.MergedDictionaries.Clear();

    // add ResourceDictionary
    this.Resources.MergedDictionaries.Add
    (
        new ResourceDictionary { Source = new Uri(String.Concat(_prefix + "Languages/English.xaml", UriKind.Relative) }
    );

where "Languages/English.xaml" is a sample relative path to selected ResourceDictionary file pertinent to your example.

Hope this may help.

Upvotes: 3

Related Questions