我该如何本地化静态ComboBox项目?

3

我有一个非常简单的ComboBox,里面包含一些x:Static项目:

<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>

这给我带来了以下内容:

正常 斜体

它与我的设置很好地绑定,可以将FontStyle应用于项目,并且我可以直接使用SelectedItem而不会有任何问题。

我的问题是:如何使用DynamicResource本地化(翻译)每个项目,同时又不失去这种方案的简单性?

我尝试从StaticExtension派生并添加另一个字符串属性来保存本地化文本并通过绑定链接回控件:

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

但是这并没有像预期的那样起作用。


帖子回复

正如@Funk所写,我可以直接使用SelectedValueSelectedValuePath来绑定到类的属性。所以我目前正在使用这个方案:

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

    <TextBlock FontStyle="Normal" Text="Normal"/>
    <TextBlock FontStyle="Italic" Text="Itálico"/>
    <TextBlock FontStyle="Oblique" Text="Oblíquo"/>
</ComboBox>
1个回答

1
你可以使用一个RichText类。
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
}

使用 SelectedValue 来更新设置。
<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>

当使用文本绑定时实现INotifyPropertyChanged。


我完全忘记了 SelectedValueSelectedValuePath。这使我可以简单地使用 TextBlock 而不是这个自定义类。谢谢。 - Nicke Manarin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接