Nicke Manarin Nicke Manarin - 1 month ago 9
C# Question

How should I localize static ComboBox items?

I have this very simple

ComboBox
with some
x:Static
items inside:

<ComboBox SelectedItem="{Binding Source={x:Static u:Settings.All}, Path=CaptionFontStyle}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock FontStyle="{Binding .}" FontSize="14" Text="{Binding .}"/>
</DataTemplate>
</ComboBox.ItemTemplate>

<x:Static Member="FontStyles.Normal"/>
<x:Static Member="FontStyles.Italic"/>
<x:Static Member="FontStyles.Oblique"/>
</ComboBox>


That gives me this:

Normal Oblique

It binds nicely to my
Settings
, the
FontStyle
can be applied to the items and I can use the
SelectedItem
directly without complications.

My problem is: How can I localize (translate) each item using a
DynamicResource
without losing the simplicity of this scheme?

I tried to derive from
StaticExtension
and simply add another string property to hold the localized text and link back to the control by binding:

<TextBlock FontStyle="{Binding .}" FontSize="14" Text="{Binding Text}"/>


But this didn't work, as expected. :/

Answer

You could use a RichText class

public class RichText
{
    #region Text Property
    private String _text = "";
    public String Text
    {
        get { return _text; }
        set { _text = value; }
    }
    #endregion Name Property

    #region FontStyle Property
    private FontStyle _fontStyle = FontStyles.Normal;
    public FontStyle FontStyle
    {
        get { return _fontStyle; }
        set { _fontStyle = value; }
    }
    #endregion FontStyle Property
}

And use SelectedValue to update Settings

<ComboBox 
    SelectedValuePath="FontStyle"
    SelectedValue="{Binding Source={x:Static u:Settings.All}, Path=CaptionFontStyle}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock FontStyle="{Binding FontStyle}" FontSize="14" Text="{Binding Text}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
    <local:RichText Text="Foo">
        <local:RichText.FontStyle>
            <x:Static Member="FontStyles.Normal"/>
        </local:RichText.FontStyle>
    </local:RichText>
    <local:RichText Text="Bar">
        <local:RichText.FontStyle>
            <x:Static Member="FontStyles.Italic"/>
        </local:RichText.FontStyle>
    </local:RichText>
    <local:RichText Text="Far">
        <local:RichText.FontStyle>
            <x:Static Member="FontStyles.Oblique"/>
        </local:RichText.FontStyle>
    </local:RichText>
</ComboBox>

Implementing INotifyPropertyChanged when using Text Bindings.