如何将DynamicResource设置为PriorityBinding?

时间:2018-02-12 09:48:57

标签: wpf xaml

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

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

不幸的是,xaml不允许在DynamicResourceStringFormat中使用FallbackValue,因此我使用了此代码:

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

我该如何处理这种情况?

1 个答案:

答案 0 :(得分:0)

只有在编译时知道格式(在您的情况下为翻译)时,使用StringFormat才有效:

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

但是,您可以使用转换器和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只不过是标记语言。