Change theme at runtime

前端 未结 5 823
一向
一向 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:32

    How you could do it:

    
        
            
                
                    
                        
                    
                
            
        
    
    public partial class App : Application
    {
        public ResourceDictionary ThemeDictionary
        {
            // You could probably get it via its name with some query logic as well.
            get { return Resources.MergedDictionaries[0]; }
        }
    
        public void ChangeTheme(Uri uri)
        {
            ThemeDictionary.MergedDictionaries.Clear();
            ThemeDictionary.MergedDictionaries.Add(new ResourceDictionary() { Source = uri });
        }
    
        //...
    }
    

    In your change method:

    var app = (App)Application.Current;
    app.ChangeTheme(new Uri("New Uri here"));
    

提交回复
热议问题