Sep 26, 2011

Localize Windows Phone 7 Styles

In process of localize silverlight application, usually, localized text wider than original english. In most cases it not a problem if You use StackPanel or other wrapping conrols, but sometimes width cannot be easely changed. In silverlight application You can use satellite assembly and put localized styles, and connect to page using MergedDictionary and ResourceDictionary.

Why cannot use same approach for Windows Phone application? There is many reasons:

  1. Windows Phone don't support satellite assemblies.
  2. Windows Phone don't care about xml:lang
  3. MergedDictionary degrade preformance
So try to use another approach. Define control, Button for example and apply default style
  1. <Button x:Name="MyStyledButton" Content="Button" Style="{StaticResource MyButton}"/>  
Then put general style in App.xaml

  1. <Style x:Key="MyButton" TargetType="Button">  
  2.     <Setter Property="Background" Value="#303030"></Setter>  
  3.     <Setter Property="BorderThickness" Value="0"></Setter>  
  4. </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.

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

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

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

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

2 comments:

  1. Thanks for your good website and for sharing your experiences.
    Phone Solutions

    ReplyDelete
  2. Ernest, have you tried the translation platform https://poeditor.com to manage your Windows localization projects? If not, I think you may find it helpful, so give it a look.

    ReplyDelete