Object Creating a skinned User Interface in WPF
Objective: To dynamically change the background color of the window (of course, it can be extended to the style of other elements)
Ideas:
- Create two resource files (resource dictionary), one for storing the default style (default. XAML), and the other for storing other styles (hothot. XAML );
- In the form to be changed (winwords in this example), use the dynamic style (... style = "{dynamicresource stylebcakground }")
- In the Application class (easy to call), add an application style public method (applyskin)
- In the main form (in this example, click an event in winwords form), call applyskin to apply the style method)
- In this example, when the winwords form is started, the applyskin method is automatically called to apply the default style (default)
OK, Code As follows:
<Home_dir> \ resources \ skins \ default. XAML 1 <! -- Background Style -->
2 < Style X: Key = "Stylebackground" >
3 < Setter Property = "Control. Background" >
4 < Setter. Value >
5 < Lineargradientbrush Startpoint = "0, 0.5" Endpoint = "1, 0.5" Opacity = "0.5" >
6 < Gradientstop Color = "Lightskyblue" Offset = "0" />
7 < Gradientstop Color = "Whitesmoke" Offset = "0.5" />
8 < Gradientstop Color = "Lightskyblue" Offset = "1" />
9 </ Lineargradientbrush >
10 </ Setter. Value >
11 </ Setter >
12 </ Style >
<Home_dir> \ resources \ skins \ hothot. XAML 1 <! -- Background Style -->
2 < Style X: Key = "Stylebackground" >
3 < Setter Property = "Control. Background" >
4 < Setter. Value >
5 < Lineargradientbrush Startpoint = "0.5, 0" Endpoint = "0.5, 1" >
6 < Gradientstop Color = "#50000000" Offset = "0.5" />
7 < Gradientstop Color = "# Ff999999" Offset = "1" />
8 </ Lineargradientbrush >
9 </ Setter. Value >
10 </ Setter >
11 </ Style >
<Home_dir> \ winwords. XAML 1
2<GridStyle="{Dynamicresource stylebackground}">
3
<Home_dir> \ winwords. XAML. CS 1 Public winwords ()
2 {
3 Initializecomponent ();
4
5 This. applyskin ("default ");
6 }
7
8 Private void applyskin (string pstrdictpath)
9 {
10 String skindictpath = @ ". \ resources \ skins \" + pstrdictpath + @ ". XAML ";
11 Uri skindicturi = new uri (skindictpath, urikind. Relative );
12
13 Myccapp APP = application. Current as myccapp;
14 App. applyskin (skindicturi );
15 }
16 Private void btntestskining_click (Object sender, routedeventargs E)
17 {
18 This. applyskin ("hothot ");
19 }
<Home_dir> \ myccapp. XAML. CS 1 Public void applyskin (URI skindictionaryuri)
2 {
3 Resourcedictionary skindict = application. loadcomponent (skindictionaryuri) as resourcedictionary;
4
5 Collection < Resourcedictionary > Mergeddicts = base. Resources. mergeddictionaries;
6
7 If (mergeddicts. Count> 0)
8 {
9 Mergeddicts. Clear ();
10 }
11
12 Mergeddicts. Add (skindict );
13 }
Where is the key? You can see it clearly. Check msdn, O, ^_^.