【问题标题】:Changing Themes Only Applies Window Background Color更改主题仅应用窗口背景颜色
【发布时间】:2017-04-09 22:31:09
【问题描述】:

这是我之前回答的问题的扩展
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

蓝色主题

红色主题

问题:
当您选择红色时,只会更改窗口背景颜色,而不会更改 TextBoxButton


组合框主题选择

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" />

【问题讨论】:

    标签: wpf visual-studio xaml


    【解决方案1】:

    MainWindow.xaml 中设置Style 属性时,使用DynamicResource 标记扩展而不是StaticResource

    <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?

    【讨论】:

    • 我已经将它应用到我的大型项目中并且运行良好。感谢您的帮助。
    猜你喜欢
    • 2010-12-03
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    • 2019-01-15
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多