Windows Phone 8 绑定到具有格式的字符串资源

2024-04-06

我的本地化资源字符串,名为TextResource具有以下值:Text: {0}. Where {0}是 String.Format 的占位符。

我的用户控件有一个名为 DependecyPropertyCount.

我想绑定Count到文本框的文本,还应用本地化字符串。这样文本块的内容就是Text: 5(假设值Count is 5)

我设法弄清楚如何绑定本地化字符串

  <TextBlock Text="{Binding Path=LocalizedResources.TextResource, Source={StaticResource LocalizedStrings}}" />

或财产价值

 <TextBlock Text="{Binding Path=Count}" />

但不能同时进行。

我怎样才能在 XAML 中做到这一点?

PS:一种选择是添加两个文本块而不是一个,但我不确定这是否是一个好的做法。


您在这里有三个选择。

第一个选项:修改视图模型以公开格式化字符串并绑定到该字符串。

public string CountFormatted {
  get {
     return String.Format(AppResources.TextResource, Count);
  }
}
<TextBlock Text="{Binding Path=CountFormatted}" />

第二个选择: 做一个转换器MyCountConverter

public class MyCountConverter: IValueConverter {
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
    if (value == null)
      return value;

    return String.Format(culture, AppResources.TextResource, value);
  }

  public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
    throw new NotImplementedException();
  }
}
<phone:PhoneApplicationPage.Resources>
    <local:MyCountConverter x:Key="MyCountConverter"/>
</phone:PhoneApplicationPage.Resources>
...
<TextBlock Text="{Binding Count, Converter={StaticResource MyCountConverter}}"/>

第三种选择:使用可绑定转换器参数,以便您可以制作一个通用的 StringFormat 转换器,您可以在其中实际绑定转换器参数。 Windows Phone 中不支持开箱即用,但仍然可行。查看this http://www.shujaat.net/2011/02/wpf-binding-converter-parameter.html有关如何完成此操作的链接。

但是,除非您使用资源来支持多种语言,否则将格式作为纯字符串传递给转换器要容易得多。

<TextBlock Text="{Binding Count, 
                  Converter={StaticResource StringFormatConverter}, 
                  ConverterParameter='Text: {0}'}" />

你必须做一个StringFormatConverter在这种情况下使用该参数的转换器。

Edit:

关于第三个选项,您可以使用IMultiValueConverter在上面的链接中实现你想要的。您可以添加以下转换器:

public class StringFormatConverter: IMultiValueConverter {
  public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
    var param = values[0].ToString();
    var format = values[1].ToString();

    return String.Format(culture, format, param);
  }

  public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) {
    throw new NotImplementedException();
  }
}
<TextBlock Text="{Binding ElementName=MultiBinder, Path=Output}" />

<binding:MultiBinding x:Name="MultiBinder" Converter="{StaticResource StringFormatConverter}"
    NumberOfInputs="2"
    Input1="{Binding Path=Count, Mode=TwoWay}"
    Input2="{Binding Path=LocalizedResources.TextResource, Source={StaticResource LocalizedStrings}}" />

我不知道这是否值得付出努力。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Windows Phone 8 绑定到具有格式的字符串资源 的相关文章

随机推荐