Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
780 views
in Technique[技术] by (71.8m points)

wpf - Change theme at runtime

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 in App.xaml:

<Application.Resources>
    <ResourceDictionary Source="/Themes/ShinyBlue.xaml"/>
</Application.Resources>

How might I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How you could do it:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary x:Name="ThemeDictionary">
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="/Themes/ShinyRed.xaml"/>
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    <!-- ... -->
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"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...