Sharker Khaleed Mahmud Silverlight Tips & Tricks

January 2, 2010

Tricks and Tips 5 : Apply styles dynamically in Silverlight

Suppose this is your simple style

App.xaml

<Application xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation
             xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml
             x:Class=”Tips.App”
             >
    <Application.Resources>
        <Style TargetType=”Grid” x:Key=”BlueColor”>
            <Setter Property=”Background” Value=”Blue” />
        </Style>      
    </Application.Resources>
</Application>

Static: (MainPage.xaml)

<UserControl xmlns:my=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data”  x:Class=”Tips.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=”300″ d:DesignWidth=”400″>
    <Grid x:Name=”LayoutRoot” Style=”{StaticResource BlueColor}”>
    </Grid>
</UserControl>

Dynamic: (MainPage.xaml.cs)

using System.Windows;
using System.Windows.Controls;

namespace Tips
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (LayoutRoot.Style == null)
            {
                LayoutRoot.Style = Application.Current.Resources["BlueColor"] as Style;
            }
        }
    }
}

Sharker Khaleed Mahmud
Sr. Software Developer
(MCP,MCTS,MCPD[web])

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.