WPF开发工具中有一种常用实现方法,就是窗口的操作。我们将会在这篇文章中为大家实现WPF窗口颜色的变更,希望对大家有所帮助。#t#
WPF窗口颜色目标:
动态变更窗口的底色(当然,可以扩展为其他元素的样式)
WPF窗口颜色变更思路:
创建两个资源文件(Resource Dictionary),一个用来存放默认样式(Default.xaml),一个用来存放其他样式(HotHot.xaml);
在需要变更样式的窗体中(本例中为:WinWords),使用动态样式(... Style="{DynamicResource styleBcakground}")
在Application类中(方便调用),添加一个应用样式的公共方法(ApplySkin)
在主窗体中(本例是在WinWords窗体中通过按钮点击事件)调用Application中应用样式方法(ApplySkin)
在本例中,WinWords窗体启动时,自动调用了ApplySkin方法来应用默认的样式(Default)
OK,WPF窗口颜色代码如下:
- < HOME_DIR>\Resources\Skins
\Default.xaml- < !-- Background Style -->
- < Style x:Key="styleBackground">
- < Setter Property="Control.Background">
- < Setter.Value>
- < LinearGradientBrush StartPoint=
"0,0.5" EndPoint="1,0.5" Opacity="0.5">- < GradientStop Color="LightSkyBlue"
Offset="0" />- < GradientStop Color=
"WhiteSmoke" Offset="0.5" />- < GradientStop Color="Light
SkyBlue" Offset="1" />- < /LinearGradientBrush>
- < /Setter.Value>
- < /Setter>
- < /Style>
- < HOME_DIR>\Resources\Skins\HotHot.xaml
- < !-- Background Style -->
- < Style x:Key="styleBackground">
- < Setter Property="Control.Background">
- < Setter.Value>
- < LinearGradientBrush StartPoint=
"0.5,0" EndPoint="0.5,1">- < GradientStop Color="#50000000"
Offset="0.5" />- < GradientStop Color="#ff999999"
Offset="1" />- < /LinearGradientBrush>
- < /Setter.Value>
- < /Setter>
- < /Style>
- < HOME_DIR>\WinWords.xaml
- < Grid Style="{DynamicResource
styleBackground}">- < HOME_DIR>\WinWords.xaml.cs
- public WinWords()
- {
- InitializeComponent();
- this.ApplySkin("Default");
- }
- private void ApplySkin(string
pstrDictPath)- {
- string skinDictPath = @".
\Resources\Skins\" + pstrDictPath
+ @".xaml";- Uri skinDictUri = new Uri(skinDict
Path, UriKind.Relative);- MyCcApp app = Application.Current
as MyCcApp;- app.ApplySkin(skinDictUri);
- }
- private void btnTestSkining_Click
(object sender, RoutedEventArgs e)- {
- this.ApplySkin("HotHot");
- }
- < HOME_DIR>\MyCcApp.xaml.cs
- public void ApplySkin(Uri
skinDictionaryUri)- {
- ResourceDictionary skinDict =
Application.LoadComponent(skin
DictionaryUri) as ResourceDictionary;- Collection< ResourceDictionary>
mergedDicts = base.Resources.
MergedDictionaries;- if (mergedDicts.Count > 0)
- {
- mergedDicts.Clear();
- }
- mergedDicts.Add(skinDict);
- }
上面介绍的内容就是WPF窗口颜色的变更实现方法。