0

I am gong to develop an windows application in .net using WPF. So, how we can implement dynamic themes at run time. I have have searched a lot about this but I can'nt understand this thing. If I add the below line in app.xaml then it shows error because how we can add thing line directly. Although there is no file exist with the name of "ExpressionDark".

<ResourceDictionary Source="Themes/ExpressionDark.xaml"/>
***or*** 
<ResourceDictionary Source="ExpressionDark.xaml"/>

Thanks in advance :)

RKK
  • 367
  • 1
  • 5
  • 10

2 Answers2

0

you can merge the theme in App.Xaml like this:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="defaulttheme.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

The defaulttheme.xaml file has to be in the root of your project. If you like to build your own project for th theme you can merge the Resources like this:

  <ResourceDictionary Source="/MyThemeProject;component/defaulttheme.xaml" />       

here defaulthteme.xaml must also be in MyThemeProject in the root and do not forget to add add reference to that project from your main project.

To build a structure you can add folders as you like.

<ResourceDictionary Source="/MyThemeProject;component/Folder1/Folder2/defaulttheme.xaml" />

To switch the themes first clear the MergedDictionaries and then add the new theme

NewTheme = new Uri(@"/MyThemeProject;component/folder1/Folder2/bluetheme.xaml", UriKind.Relative);

Application.Current.Resources.MergedDictionaries.Clear();
Application.Current.Resources.MergedDictionaries.Add(NewTheme); 

Regards

flusser

flusser
  • 77
  • 4
0

Assuming that by DynamicThemes, you mean to put themes at run-time, the best possible way it to load the resource dictionary, full of control styles into resource of main application or any control.

    public static ResourceDictionary GetThemeResourceDictionary(Uri theme)
    {
        if (theme != null)
        {
            return Application.LoadComponent(theme) as ResourceDictionary;
        }
        return null;
    }

    public static void ApplyTheme(this ContentControl control /* Change this to Application to use this function at app level */, string theme)
    {
        ResourceDictionary dictionary = GetThemeResourceDictionary(theme);

        if (dictionary != null)
        {
            // Be careful here, you'll need to implement some logic to prevent errors.
            control.Resources.MergedDictionaries.Clear();
            control.Resources.MergedDictionaries.Add(dictionary);
            // For app level
            // app.Resources.MergedDictionaries.Clear();
            // app.Resources.MergedDictionaries.Add(dictionary);

        }
    }
Code0987
  • 2,598
  • 3
  • 33
  • 51