WPF窗口顏色變更方法
WPF開發(fā)工具中有一種常用實現(xiàn)方法,就是窗口的操作。我們將會在這篇文章中為大家實現(xiàn)WPF窗口顏色的變更,希望對大家有所幫助。#t#
WPF窗口顏色目標(biāo):
動態(tài)變更窗口的底色(當(dāng)然,可以擴(kuò)展為其他元素的樣式)
WPF窗口顏色變更思路:
創(chuàng)建兩個資源文件(Resource Dictionary),一個用來存放默認(rèn)樣式(Default.xaml),一個用來存放其他樣式(HotHot.xaml);
在需要變更樣式的窗體中(本例中為:WinWords),使用動態(tài)樣式(... Style="{DynamicResource styleBcakground}")
在Application類中(方便調(diào)用),添加一個應(yīng)用樣式的公共方法(ApplySkin)
在主窗體中(本例是在WinWords窗體中通過按鈕點擊事件)調(diào)用Application中應(yīng)用樣式方法(ApplySkin)
在本例中,WinWords窗體啟動時,自動調(diào)用了ApplySkin方法來應(yīng)用默認(rèn)的樣式(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);
- }
上面介紹的內(nèi)容就是WPF窗口顏色的變更實現(xiàn)方法。