65.9K
CodeProject is changing. Read more.
Home

Localize ToggleSwitch in the Silverlight Toolkit

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Jun 19, 2013

CPOL
viewsIcon

10320

Localize ToggleSwitch in the Silverlight Toolkit.

I've read tons of blogs and questions and answers, but cannot get to localize the ToggleSwitch in the Silverlight Toolkit in my Windows Phone application. So I decided to get my own way. My proposal is based on a DataTemplate for ToggleSwitch and ValueConverter. So let's go.

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

The next step is to create the ValueConverter:

public class BoolToSwitchConverter : IValueConverter  
{  
    private string FalseValue = Resources.Off;  
    private string TrueValue  = Resources.On;  
  
    public object Convert(object value, Type targetType, 
           object parameter, System.Globalization.CultureInfo culture)  
    {  
        if (value == null)  
            return FalseValue;  
        else  
            return ("On".Equals(value)) ? TrueValue : FalseValue;  
    }  
  
    public object ConvertBack(object value, Type targetType, 
           object parameter, System.Globalization.CultureInfo culture)  
    {  
        return value != null ? value.Equals(TrueValue) : false;  
    }  
}

Make our converter visible from XAML, adding glue code to Application Resources in App.xaml. Add a link to the app namespace if you do not have it already, do this before xmlns:local="clr-namespace:AppNamspace". And add the resource code:

<Application.Resources>  
    <local:BoolToSwitchConverter x:Key="Switch" />  
</Application.Resources>

And finally override the DataTemplate on our ToggleSwitch:

<toolkit:ToggleSwitch x:Name="MySwitch" Header="Localized Switch">  
    <toolkit:ToggleSwitch.ContentTemplate>  
        <DataTemplate>  
            <ContentControl HorizontalAlignment="Left"   
                Content="{Binding Converter={StaticResource Switch}}"/>  
        </DataTemplate>  
    </toolkit:ToggleSwitch.ContentTemplate>  
</toolkit:ToggleSwitch>

Result: