The project I am working on has a rich text box that can have it’s font changed to any of the system fonts via a combo box.
We add all the FontFamily objects from “Fonts.SystemFontFamilies” as the ItemsSource of the combo box. We need to be able to show the localized names of these fonts if they exist within each FontFamily.
I’m currently assuming that the text we see displayed for each ComboBoxItem is the Source property of the FontFamily objects we set as the ItemsSource. Is there a simple way to localize this source? I have been able to get the localized names using:
font.FamilyNames.TryGetValue(XmlLanguage.GetLanguage("ja-JP"), out name);
but as FontFamily.Source is readonly, I am unable to assign this new name to the FontFamily objects.
— UPDATE —
We have decided not to use a class that contains a font family due to complications with integrating it with the application. I want to try using a value converter to avoid having to change the underlying code.
I have the following value converter class:
class FontValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
FontFamily font = (FontFamily)value;
string localizedName = font.FamilyNames[XmlLanguage.GetLanguage(culture.Name)];
if (!String.IsNullOrEmpty(localizedName))
return localizedName;
return font.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException("ConvertBack not supported");
}
}
I am trying to bind this to the ComboBoxItem objects. We set the ItemsSource in the code behind file; basically “ItemsSource = collectionOfFonts”. What I want to do is bind my converter to each item in ItemsSource so that it will converter to the localized font family name.
I have been considering the following XAML:
<Style
x:Key="ComboBoxItemStyle"
TargetType="{x:Type ComboBoxItem}">
<Setter
Property="Template">
<Setter.Value>
<ControlTemplate
TargetType="{x:Type ComboBoxItem}">
<ContentPresenter
Content="{Binding Source=..., Converter={StaticResource FontValueConverter}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
However, I am confused as to how I can bind so it retrieves a FontFamily object and converts it to a string to return as the value to be displayed.
Any thoughts?
We discovered the simplest solution that requires minimal changes to the rest of the application was to instantiate a new FontFamily object using the localized name of the font if available. This was done by creating the following method which returns a new FontFamily object if necessary:
Using this approach meant that we only had to alter the code where the items are added to the combo box and required absolutely no changes elsewhere.
Example of use: