Iris Classon
Iris Classon - In Love with Code

Example Metro app /WinRT: Change/switch styles or datatemplates at runtime using code behind

I was asked on Twitter last week how style or content template can be changed at runtime and I never got around to publish the example. I’ve shown plenty of examples how a style can be changed, but not how you can switch between styles or content templates. I have to examples for you but I’ll post them separately.

Changing from a gray button (boring button)

To a red (party button)

In the first example I will set the style of a button in code behind from one predefined style to another (defined in the resource dictionary).

Resourcedictionary, the two styles

[sourcecode language=“XML”]

<Style x:Key="GrayStyle" TargetType="Button">  
    <Setter Property="Background" Value="SlateGray"/>  


The mainview

[sourcecode language=“XML”]


<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">  
        <Button x:Name="theButton" Style="{Binding BtnStyle}"   Width="500" Height="500" VerticalAlignment="Center" HorizontalAlignment="Center" Click="theButton\_Click"/>  

The code behind

[sourcecode language=“csharp”]
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace StyleSwitcher

public sealed partial class MainPage : Page  
    public MainPage()  
        theButton.Style = Application.Current.Resources["GrayStyle"] as Style;  

    protected override void OnNavigatedTo(NavigationEventArgs e)  

    private void theButton\_Click(object sender, RoutedEventArgs e)  
        var res = new ResourceDictionary()  
                         Source = new Uri("ms-appx:///Common/StandardStyles.xaml", UriKind.Absolute)  
        theButton.Style = res["RedStyle"] as Style;  

        theButton.Style = Application.Current.Resources["RedStyle"] as Style;  




Leave a comment below, or by email.
2/11/2013 4:44:18 AM
this Solution helped me so much thx iris 
Iris Classon
2/11/2013 9:23:46 AM
Reply to: serkan
Thank you! - And glad to hear that =) 
3/4/2013 6:02:42 PM
this Solution helped me too, thx iris 

Last modified on 2012-08-21

comments powered by Disqus