Changing Themes Only Applies Window Background Col

2019-09-13 23:51发布

This is an extension to my previous answered question
How to Change Theme XAML with ComboBox?


I have a ComboBox that changes Themes between ThemeBlue.xaml and ThemeRed.xaml.

Here's the example project file:
https://drive.google.com/open?id=0BycnCTAQ1U7gSU5kUUdaNzRIZDg

ThemeBlue.xaml: https://kopy.io/8HcDd
ThemeRed.xaml: https://kopy.io/iWWLC

Blue Theme

Blue Theme

Red Theme

Problem:
When you choose Red, only the Window Background color is changed, but not the TextBox or Button.

Red Theme


ComboBox Theme Select

XAML

<ComboBox x:Name="cboTheme" Style="{StaticResource ComboBoxCustom}" HorizontalAlignment="Left" Margin="199,120,0,0" VerticalAlignment="Top" Width="75" SelectionChanged="themeSelect_SelectionChanged">
    <System:String>Blue</System:String>
    <System:String>Red</System:String>
    <System:String>Purple</System:String>
</ComboBox>

C#

private void cboTheme_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string theme = cboTheme.SelectedItem.ToString();

    App.Current.Resources.MergedDictionaries.Clear();
    App.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("Theme" + theme + ".xaml", UriKind.RelativeOrAbsolute) });

    // Save Theme for next launch
    Settings.Default["Theme"] = cboTheme.SelectedItem.ToString();
    Settings.Default.Save();
}

App.xaml

The theme file is loaded through App.xaml at startup

<Application x:Class="MultiTheme.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:MultiTheme"
             StartupUri="MainWindow.xaml">

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

</Application>

MainWindow.xaml

A TextBox with the Theme Style applied:

<TextBox x:Name="textBox1" Style="{StaticResource TextBoxCustom}" HorizontalAlignment="Left" Height="22" Margin="93,43,0,0" Width="464" />

1条回答
迷人小祖宗
2楼-- · 2019-09-14 00:29

Use the DynamicResource markup extension instead of StaticResource when you set the Style properties in MainWindow.xaml:

<Button x:Name="button" Style="{DynamicResource ButtonCustom}" Content="Button" HorizontalAlignment="Left" Margin="304,171,0,0" VerticalAlignment="Top" Width="75"/>
<TextBox x:Name="textBox" Style="{DynamicResource TextBoxCustom}" HorizontalAlignment="Left" Height="78" Margin="28,77,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="351"/>

What's the difference between StaticResource and DynamicResource in WPF?

查看更多
登录 后发表回答