Search code examples
c#wpfpathresourcedictionary

Use string from App.Resources as the value for a ResourceDictionary's Source property {WPF}


I wanted to implement multiple languages in my application without using a Resources file (*.resx), and I wanted to use a separate ResourceDictionary for this, Text/en-US.xaml. Since I wanted the language to update all at once, I made each Window, Page, etc. to set their Resources property to a ResourceDictionary, whose source is the path of the language file.

First, I tried setting the container's Resources property to a ResourceDictionary, and the Source property of that resource dictionary used the curly brace resource mechanism, like this:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.Resources>
        <ResourceDictionary Source="{DynamicResource AppLangPath}"/>
    </Window.Resources>
</Window>

However, at Line 4 of that code, the Source property has the error underline, and the name AppLangPath doesn't even appear in IntelliSense. However, I was expecting there to be no underline, and for the name to appear in IntelliSense, and for the strings located in en-US.xaml to be shown in IntelliSense too.


Solution

  • I am afraid you cannot set the Source property of a ResourceDictionary using the DynamicResource markup extension in XAML because it's not a dependency property.

    To switch language you should programmatically replace one ResourceDictionary with another one, e.g.:

    this.Resources.Clear(); //this refers to the window
    this.Resources.MergedDictionaries.Add(new ResourceDictionary()
    {
        Source = new Uri("Text/sv-SE.xaml", UriKind.RelativeOrAbsolute)
    });