Dynamic switching of theme in SILVERLIGHT4

Source: Internet
Author: User

Silverlight is generally used to develop some enterprise application system, if the user has been facing the same style of the page, the time is inevitably tired, so generally will provide several styles and theme for the user to select, the following is how to do not re-login system, the implementation of the style of dynamic switching. Let's write a demo to illustrate.

Create a new Silverlight project and add a default site, first write the page, for simplicity, just put two controls, mainpage code is as follows:

<UserControlx:class= "Silverlightchangetheme.mainpage"xmlns= "Http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d= "http://schemas.microsoft.com/expression/blend/2008"XMLNS:MC= "http://schemas.openxmlformats.org/markup-compatibility/2006"mc:ignorable= "D"D:designheight= "+"D:designwidth= "The ">    <Gridx:name= "LayoutRoot"Background= "White">      <ButtonContent= "Changetheme"Height= "All"HorizontalAlignment= "Left"Margin= "40,66,0,0"Name= "Button1"VerticalAlignment= "Top"Width= "108"Click= "Button1_Click"Style="{StaticResource Btnstyle}" />      <TextBlockHeight= "All"HorizontalAlignment= "Left"Margin= "58,37,0,0"Name= "TextBlock1"Text= "Text Style"VerticalAlignment= "Top"FontSize= "+"Width= "101"Style="{StaticResource Txtstyle}" />   </Grid></UserControl>

As follows:

is a simple button and a TextBlock, the following to achieve the effect is to click the button to achieve the text and button font color change ( style to load from the resource file );

So since to achieve the switch style, first of all to have a resource file, we first built two Silverlight Resource Dictionary, red style and blue style, named Blue.xaml and Red.xaml, the code is as follows:

Red.xaml:

<ResourceDictionaryxmlns= "Http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml">   <StyleTargetType= "button"x:key= "Btnstyle">      <Setter Property= "Foreground"Value= "Red" />   </Style>   <StyleTargetType= "TextBlock"x:key= "Txtstyle">      <Setter Property= "Foreground"Value= "Red" />   </Style></ResourceDictionary>

Blue.xaml:

<ResourceDictionaryxmlns= "Http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml">   <StyleTargetType= "button"x:key= "Btnstyle">      <Setter Property= "Foreground"Value= "Blue" />   </Style>   <StyleTargetType= "TextBlock"x:key= "Txtstyle">      <Setter Property= "Foreground"Value= "Blue" />   </Style></ResourceDictionary>

Since the style in the resource file is already bound in the mainpage, the system must load a style file at startup, which is called the default style, so add a static class to load the default style and switch style when the system starts up, the code is as follows:

ThemeHelper.cs

usingSystem;usingSystem.Net;usingSystem.Windows;usingSystem.Windows.Controls;usingSystem.Windows.Documents;usingSystem.Windows.Ink;usingSystem.Windows.Input;usingSystem.Windows.Media;usingSystem.Windows.Media.Animation;usingSystem.Windows.Shapes;namespacesilverlightchangetheme{ Public Static classThemehelper {/// <summary>      ///load style files to Application.Current.Resources/// </summary>      /// <param name= "theme" ></param>       Public Static voidLoadtheme (stringtheme) {ResourceDictionary rd=NewResourceDictionary (); if(Theme. Length = =3) {application.loadcomponent (rd,NewUri ("/silverlightchangetheme;component/red.xaml", urikind.relative)); }         Else{application.loadcomponent (rd,NewUri ("/silverlightchangetheme;component/blue.xaml", urikind.relative)); }         //empty the Application.Current.Resources and store the new style         if(Application.Current.Resources.Count >0) {Application.Current.Resources.Clear ();      } Application.Current.Resources.MergedDictionaries.Add (RD); }      /// <summary>      ///gets the style of the specified name from the Application.Current.Resources/// </summary>      /// <param name= "name" ></param>      /// <returns></returns>       Public Static ObjectFindResource (stringname) {         if(App.Current.Resources.Contains (name)) {returnApp.current.resources[name]; }         Else         {            return NULL;//This returns null if no control becomes the system default style.          }      }   }}

Then in App.xaml.cs, add the following code to the Application_Startup method:

Private void Application_Startup (object  sender, StartupEventArgs e)      {         // load Default style         themehelper.loadtheme ("Blue");           This New MainPage ();      }

This will automatically load the blue style at startup, under:

Then, add an event to the MainPage button to implement the style switch, the code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net;usingSystem.Windows;usingSystem.Windows.Controls;usingSystem.Windows.Documents;usingSystem.Windows.Input;usingSystem.Windows.Media;usingSystem.Windows.Media.Animation;usingSystem.Windows.Shapes;namespacesilverlightchangetheme{ Public Partial classMainpage:usercontrol {BOOLisred =false;  PublicMainPage () {InitializeComponent (); }      Private voidButton1_Click (Objectsender, RoutedEventArgs e) {         if(isred) {//load style to Application.Current.ResourcesThemehelper.loadtheme ("Blue"); Isred=false; }         Else         {            //load style to Application.Current.ResourcesThemehelper.loadtheme ("Red"); Isred=true; }         //at run time, the update style must reset the style of each control, and then call this. UpdateLayout () method update page. Button1. Style = Themehelper.findresource ("Btnstyle") asStyle; Textblock1.style= Themehelper.findresource ("Txtstyle") asStyle;  This.      UpdateLayout (); }   }}

This allows the style to be switched, and it is important to note that the system switches style after boot, to reset the style of each control in the code, and then call this. UpdateLayout () method update page.

Of course, if you have more than one form, you don't need to set it up, you just need to set the controls that are already displayed.

Additional knowledge:

The syntax for URI paths.

Relative URI access to the XAML file, such as <image source= "Silverlight.png"/> or <image source= "./silverlight.png"/>

In sub-folders can be used <image source= "./images/sl.jpg"/> Access to
The safest way is to use the unique assembly resource URI access, in the format
<image source= "/{assemblyshortname};component/foo.jpg"/> this way you can also refer to pictures in other assemblies in the XAP

Modify our two images to refer to the way

<Image Source="/SilverlightApplication1;component/silverlight.png"/>
<Image Source="/SilverlightApplication1;component/images/sl.jpg" Height="100"/>  

Click here to download the source code

Dynamic switching of theme in SILVERLIGHT4

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.