65.9K
CodeProject is changing. Read more.
Home

Localize Windows Phone 7 Styles

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.93/5 (4 votes)

Jun 19, 2013

CPOL
viewsIcon

4963

Localize Windows Phone 7 Styles.

Introduction

In the process of localizing a Silverlight application, usually, localized text is wider than the original English text. In most cases this is not a problem if you use a StackPanel or other wrapping controls, but sometimes width cannot be easily changed. In a Silverlight application you can use a satellite assembly and put localized styles, and connect to a page using MergedDictionary and ResourceDictionary.

Why cannot we use the same approach for Windows Phone applications? There are many reasons:

  1. Windows Phone doesn't support satellite assemblies.
  2. Windows Phone doesn't care about xml:lang.
  3. MergedDictionary degrades performance.

So try to use another approach. Define a control, a Button for example and apply the default style:

<Button x:Name="MyStyledButton" Content="Button" Style="{StaticResource MyButton}"/>

Then put a general style in App.xaml:

<Style x:Key="MyButton" TargetType="Button">  
    <Setter Property="Background" Value="#303030"></Setter>  
    <Setter Property="BorderThickness" Value="0"></Setter>  
</Style>

Another bug in Windows Phone 7 that attribute BasedOn not supported, so we have to copy whole style to derived. Next step change name, adding -[lang code] to x:Key of style. So 'MyButton' will be 'MyButton-de' for example.

<Style x:Key="MyButton-ru" TargetType="Button">  
    <Setter Property="Background" Value="#FF8080"></Setter>  
    <Setter Property="BorderThickness" Value="1"></Setter>  
</Style>

Next we'll add runtime code for loading language dependent styles.

string lang = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;  
// load localized style  
Style style = (Style)App.Current.Resources["MyButton-" + lang];  
if (style != null)  
{  
    MyButton.Style = style;  
}

At runtime we determine the current UI language and try to load the altered style. If found, apply the new style, if not - the hardcoded style will be used.