如何将 DynamicResource 设置为 PriorityBinding? [英] How to set a DynamicResource as PriorityBinding?

查看:23
本文介绍了如何将 DynamicResource 设置为 PriorityBinding?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多语言应用程序,其中包含两个字典 en.xamlit.xaml,假设我有以下情况:

I have a multilanguage application which contains two dictionary en.xaml and it.xaml, suppose that I have the following situation:

我需要在 TextBlock 中显示默认文本,例如:Contact saved 0 in memory 使用包含上述文本的 DynamicResource 键.

I need to display a default text in a TextBlock such as: Contact saved 0 in memory using a DynamicResource key that contains the text above.

不幸的是,xaml 不允许在 StringFormatFallbackValue 中使用 DynamicResource 所以我使用了这个代码:

Unfortunately xaml doesn't allow to use DynamicResource in a StringFormat or as FallbackValue so I used this code:

<TextBlock Tag="{DynamicResource defaultContactStr}">
  <TextBlock.Text>
    <PriorityBinding>
     <Binding Path="ContactSaved" />
     <Binding Path="Tag" RelativeSource="{RelativeSource Mode=Self}" />
   </PriorityBinding>
 </TextBlock.Text>

这将只显示 0 这是属性 ContactSaved 的默认值,但我需要显示:Contact saved 0 in memory, 或者如果值发生变化:Contact saved 5 in memory 等等...

this will display only 0 which is the default value of the proeprty ContactSaved, but I need to display: Contact saved 0 in memory, or if the value change: Contact saved 5 in memory etc...

我该如何处理这种情况?

how can I manage this situation?

推荐答案

使用 StringFormat 仅在编译时已知格式(您的情况下的翻译)时才有效:

Using a StringFormat works only if the format (the translation in your case) is known at compile-time:

<TextBlock>
    <TextBlock.Text>
        <Binding Path="ContactSaved" StringFormat="{}Contact saved {0} in memory" />
    </TextBlock.Text>
</TextBlock>

否则,您可以使用转换器和 MultiBinding 来处理此问题:

Othwerwise you may handle this using a converter and a MultiBinding:

public class CustomConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        string resource = values[0] as string;
        string contactSaved = values[1].ToString();

        return string.Format(resource, contactSaved);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML:

<TextBlock Tag="{DynamicResource defaultContactStr}">
    <TextBlock.Text>
        <MultiBinding>
            <MultiBinding.Converter>
                <local:CustomConverter />
            </MultiBinding.Converter>
            <Binding Path="Tag" RelativeSource="{RelativeSource Mode=Self}" />
            <Binding Path="ContactSaved" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

en.xaml:

<system:String x:Key="defaultContactStr">Contact saved {0} in memory</system:String>

请记住,XAML 只不过是一种标记语言.

Remember that XAML is nothing but a markup language.

这篇关于如何将 DynamicResource 设置为 PriorityBinding?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆