Unlike controls located in the FCL, the Toolkit does not ship with localized resources. In the case of the ToggleSwitch
, it is something to be mindful of because of the default Header
values: Off and On, which must be localized if you want to support other languages.
You could take the Toolkit source code and provide a localized resource dictionary for each language you want to support. This, however, would leave you having to update each new version of the Toolkit with your custom dictionaries—not the best approach.
An alternative approach is to use a custom IValueConverter
to populate the Content
property of the ToggleSwitch
based on the value of its IsChecked
property. Depending on the value of its IsChecked
property, we display a particular localized string from a resource dictionary (see Listing 9.5).
For more information on localizing Windows Phone apps, see Chapter 19, “Supporting Multiple Cultures and Languages.”
public class LocalizedToggleSwitchConverter : IValueConverter
{
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
bool? toggleOn = (bool?)value;
return toggleOn.HasValue && toggleOn.Value
? MainResources.ToggleSwitch_Checked
: MainResources.ToggleSwitch_Unchecked;
}
public object ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
The IValueConverter
can be declared as an application resource by placing it in your app’s App.xaml file or in a referenced ResourceDictionary
. This allows it to be used throughout your app. Alternatively, it can be defined within your page, as shown:
<phone:PhoneApplicationPage.Resources>
<e:LocalizedToggleSwitchConverter
x:Name="LocalizedToggleSwitchConverter" />
</phone:PhoneApplicationPage.Resources>
Once in place, a ToggleSwitch
can bind to the viewmodel value representing the checked state and use the IValueConverter
to populate the Content
property, as shown:
<toolkit:ToggleSwitch
Header="Localizable ToggleSwitch"
IsChecked="{Binding ToggleOn, Mode=TwoWay}"
Content="{Binding ToggleOn,
Converter={StaticResource LocalizedToggleSwitchConverter}}" />
Just as the HeaderTemplate
property is used to customize how the control’s header is displayed, the ContentTemplate
is used to customize how the Content
property is displayed.
18.221.198.132