3

名前付きのローカライズされたリソース文字列TextResourceの値はText: {0}. {0}String.Format のプレースホルダーはどこにありますか。

私のユーザー コントロールには、 という名前の DependecyProperty がありCountます。

Countテキスト ボックスのテキストにバインドするだけでなく、ローカライズされた文字列も適用したいと考えています。そのため、テキスト ブロックの内容はText: 5(の値Countが 5 であると仮定)

ローカライズされた文字列をバインドする方法を理解することができました

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

またはプロパティ値

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

両方同時にではありません。

XAMLでそれを行うにはどうすればよいですか?

PS: 1 つのオプションとして、テキスト ブロックを 1 つではなく 2 つ追加することもできますが、それが良い方法かどうかはわかりません。

4

1 に答える 1

6

ここには 3 つのオプションがあります。

最初のオプション:ビューモデルを変更して、フォーマットされた文字列を公開し、それにバインドします。

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

2 番目のオプション: コンバーターを作成する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}}"/>

3 番目のオプション: バインド可能なコンバーター パラメーターを使用して、コンバーター パラメーターを実際にバインドできる一般的な StringFormat コンバーターを作成できるようにします。これは、Windows Phone ではそのままではサポートされていませんが、実行可能です。方法については、このリンクを確認してください。

ただし、複数の言語をサポートするためにリソースを使用している場合を除き、形式を単純な文字列としてコンバーターに渡す方がはるかに簡単です。

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

StringFormatConverterこの場合、パラメーターを使用するコンバーターを作成する必要があります。

編集:

3番目のオプションについては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}}" />

努力する価値があるかどうかはわかりませんが。

于 2013-05-20T06:23:03.093 に答える