Changing ThemeResources dynamically in UWP

Please check ResourceDictionary and XAML resource references official document, you could edit SystemAccentColor ResourceDictionary content in the code behind. But we need place the code in the Application.OnLaunched method

protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    Frame rootFrame = Window.Current.Content as Frame;
    if (rootFrame == null)
    {
        SolidColorBrush brush = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 0, 255, 0)); // green
        this.Resources["brush"] = brush;
        // … Other code that VS generates for you …
    }
}

If you want to make it change at real time, we suggest use setting class to achieve

for example

public class Setting : INotifyPropertyChanged
{
    private SolidColorBrush accentColor = new SolidColorBrush( Colors.Red);
    public SolidColorBrush AccentColor
    {
        get { return accentColor; }
        set { accentColor = value; OnPropertyChanged(); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

xaml

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary>
                <local:Setting x:Key="Setting"/>
            </ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>


<Button
    VerticalAlignment="Bottom"
    Background="{Binding AccentColor, Mode=TwoWay, Source={StaticResource Setting}}"
    Click="Button_Click"
    Content="Click" />

Update the value at runtime

((Setting)Application.Current.Resources["Setting"]).AccentColor = new SolidColorBrush(Colors.Beige) ;

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top