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"/>
</Style>
[/sourcecode]
The mainview
[sourcecode language=“XML”]
<Page.Resources>
</Page.Resources>
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<StackPanel>
<Button x:Name="theButton" Style="{Binding BtnStyle}" Width="500" Height="500" VerticalAlignment="Center" HorizontalAlignment="Center" Click="theButton\_Click"/>
</StackPanel>
</Grid>
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()
{
this.InitializeComponent();
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;
}
}
}
[/sourcecode]
Comments
this Solution helped me too, thx iris
Last modified on 2012-08-21