开发者

How to apply different color schemes in a WPF application

Is there a way to replace all the brush definitions for a WPF application at runtime, and only declare the styles that use it once? This would be useful for different color schemes, but keep the same UI and declare it once. All the examples I can find duplicate the 开发者_运维技巧styles in the different theme files - is this the only way to do it?

Little example:

Blue.xaml

<SolidColorBrush x:Key="DefaultBackgroundBrush" Color="Blue"/>

Yellow.xaml

<SolidColorBrush x:Key="DefaultBackgroundBrush" Color="Yellow"/>

generic.xaml?

<Style TargetType="{x:Type Button}">
  <Setter Property="Background" Value="{StaticResource DefaultBackgroundBrush}" />
</Style>


Figured it out myself just after posting the question, often like that ;)

The code below was for testing, so don't mind the un-sexyness of it:

private void MenuItemBlue_Click(object sender, RoutedEventArgs e)
{
    ResourceDictionary genericSkin = new ResourceDictionary();
    genericSkin.Source = new Uri(@"/Themes/" + "generic" + ".xaml", UriKind.Relative);

    ResourceDictionary blueSkin = new ResourceDictionary();
    blueSkin.Source = new Uri(@"/Themes/" + "blue" + ".xaml", UriKind.Relative);

    Application.Current.Resources.MergedDictionaries.Clear();

    Application.Current.Resources.MergedDictionaries.Add(genericSkin);
    Application.Current.Resources.MergedDictionaries.Add(blueSkin);
}

And change the style defined in "generic.xaml" to DynamicResource

<Style TargetType="{x:Type Button}">
    <Setter Property="Background" Value="{DynamicResource defaultColor}" />
</Style>

Other suggestions are most welcome though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜