这是我之前回答的问题的扩展 How to Change Theme XAML with ComboBox?
我有ComboBox
更改ThemeBlue.xaml
和ThemeRed.xaml
之间的主题。
这是示例项目文件:
https://drive.google.com/open?id=0BycnCTAQ1U7gSU5kUUdaNzRIZDg
ThemeBlue.xaml:https://kopy.io/8HcDd
ThemeRed.xaml:https://kopy.io/iWWLC
蓝色主题
红色主题
问题:
选择红色时,仅更改窗口背景颜色,但不更改TextBox
或Button
。
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
加载
<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>
应用了主题样式的TextBox
:
<TextBox x:Name="textBox1" Style="{StaticResource TextBoxCustom}" HorizontalAlignment="Left" Height="22" Margin="93,43,0,0" Width="464" />
答案 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?