Change theme at runtime

前端 未结 5 828
一向
一向 2020-11-30 01:48

I have a WPF application with a theme (ShinyRed.xaml) and I want to have a button that when clicked changes the theme to ShinyBlue.xaml

I load in the theme initially

5条回答
  •  一向
    一向 (楼主)
    2020-11-30 02:44

    H.B.'s answer did not run for me, I had to do this (works, tested):

    Uri dictUri = new Uri(@"/Resources/Themes/MyTheme.xaml", UriKind.Relative);
    ResourceDictionary resourceDict = Application.LoadComponent(dictUri) as ResourceDictionary;
    Application.Current.Resources.MergedDictionaries.Clear();
    Application.Current.Resources.MergedDictionaries.Add(resourceDict);
    

    To pretty it up:

    // Place in App.xaml.cs
    public void ChangeTheme(Uri uri)
    {
        ResourceDictionary resourceDict = Application.LoadComponent(uri) as ResourceDictionary;
        Application.Current.Resources.MergedDictionaries.Clear();
        Application.Current.Resources.MergedDictionaries.Add(resourceDict);
    }
    
    // Example Usage (anywhere in app)
    private void ThemeRed_Click(object sender, RoutedEventArgs e)
    {
        var app = App.Current as App;
        app.ChangeTheme(new Uri(@"/Resources/Themes/RedTheme.xaml", UriKind.Relative));      
    }
    

提交回复
热议问题