仅更改主题应用窗口背景颜色

时间:2017-04-09 14:28:07

标签: wpf visual-studio xaml

这是我之前回答的问题的扩展  How to Change Theme XAML with ComboBox?

我有ComboBox更改ThemeBlue.xamlThemeRed.xaml之间的主题。

这是示例项目文件:
https://drive.google.com/open?id=0BycnCTAQ1U7gSU5kUUdaNzRIZDg

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

蓝色主题

Blue Theme

红色主题

问题:
选择红色时,仅更改窗口背景颜色,但不更改TextBoxButton

Red Theme

ComboBox主题选择

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

主题文件在启动时通过App.xaml加载

<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

应用了主题样式的TextBox

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

1 个答案:

答案 0 :(得分:1)

DynamicResource中设置StaticResource属性时,使用Style标记扩展名而不是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?