Sep 28, 2011

Localize ToggleSwitch in Silverlight Toolkit

Read tons of blogs and questions and answers, but cannot get Localize ToggleSwitch in SilverLight Toolkit in my Windows Phone Application. So i decided to get my own way. My proposal based on DataTemplate for ToggleSwitch and ValueConverter. So let's go.

First add Localized Resource for our new On and Off string values:


Next step create ValueConverter:
  1. public class BoolToSwitchConverter : IValueConverter  
  2. {  
  3.     private string FalseValue = Resources.Off;  
  4.     private string TrueValue  = Resources.On;  
  5.   
  6.     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)  
  7.     {  
  8.         if (value == null)  
  9.             return FalseValue;  
  10.         else  
  11.             return ("On".Equals(value)) ? TrueValue : FalseValue;  
  12.     }  
  13.   
  14.     public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)  
  15.     {  
  16.         return value != null ? value.Equals(TrueValue) : false;  
  17.     }  
  18. }  
Make our converter visible from XAML, adding glue code to Application Resources in App.xaml Add link to app namespace if you not do this before xmlns:local="clr-namespace:AppNamspace" And add resource code
  1. <Application.Resources>  
  2.     <local:BoolToSwitchConverter x:Key="Switch" />  
  3. </Application.Resources>  
And finally override DataTemplate on our ToggleSwitch:
  1. <toolkit:ToggleSwitch x:Name="MySwitch" Header="Localized Switch">  
  2.     <toolkit:ToggleSwitch.ContentTemplate>  
  3.         <DataTemplate>  
  4.             <ContentControl HorizontalAlignment="Left"   
  5.                 Content="{Binding Converter={StaticResource Switch}}"/>  
  6.         </DataTemplate>  
  7.     </toolkit:ToggleSwitch.ContentTemplate>  
  8. </toolkit:ToggleSwitch>  
Result:

2 comments:

  1. "Maybe" that issue was fixed: http://silverlight.codeplex.com/workitem/10164

    Not sure if fix is already released or if you have to compile WPToolKit by yourself.

    I guess your solution works but in my view "On".Equals(value) looks strange ...

    ReplyDelete
  2. A good blog always comes-up with new and exciting information and while reading I have feel that this blog is really have all those quality that qualify a blog to be a one. GDPR toolkit

    ReplyDelete