2017-03-13 5 views
1

xamarin localization topicとサンプルTodoLocalizedに続いて、私は多言語のアプリを作った。私の問題はときどき、時には大文字の単語を使う必要があり、同じ単語の大文字のバージョンとしてresxファイルに別の翻訳を作成したくない。これを達成する最善の方法は何ですか?可能であれば、このtranslate拡張を拡張しますか? IValueConvertorを使うべきですか?はい、XAMLでxamarin.formsのxamlで大文字/小文字のresxバインディングを使用する方法は?

// You exclude the 'Extension' suffix when using in Xaml markup 
     [ContentProperty("Text")] 
     public class TranslateExtension : IMarkupExtension 
     { 
      readonly CultureInfo ci; 
      const string ResourceId = "myApp.Resx.AppRes"; 

      public TranslateExtension() 
      { 
       if (Device.OS == TargetPlatform.iOS || Device.OS == TargetPlatform.Android) 
       { 
        ci = DependencyService.Get<ILocalize>().GetCurrentCultureInfo(); 
       } 
      } 

      public string Text { get; set; } 

      public object ProvideValue(IServiceProvider serviceProvider) 
      { 
       if (Text == null) 
        return ""; 

       ResourceManager resmgr = new ResourceManager(ResourceId 
            , typeof(TranslateExtension).GetTypeInfo().Assembly); 

       var translation = resmgr.GetString(Text, ci); 

       if (translation == null) 
       { 
#if DEBUG 
        throw new ArgumentException(
         String.Format("Key '{0}' was not found in resources '{1}' for culture '{2}'.", Text, ResourceId, ci.Name), 
         "Text"); 
#else 
       translation = Text; // HACK: returns the key, which GETS DISPLAYED TO THE USER 
#endif 
       } 
       return translation; 
      } 
     } 

私のXAMLを、それをバインドする方法場合:

 <Button Image="ic_add.png" Text="{resx:Translate AddNew}" 
Command="{Binding AddNew}" HorizontalOptions="FillAndExpand"/> 

私はこれをやってみましたが、私はバインディングの推測では、BindingContextをで定義されたプロパティを期待しています。したがって、それは動作しませんが、どのように私はresxファイルで定義されたテキストのためにそれを達成するのですか? 、

<Button Text="{Binding Converter={StaticResource UpperCaseConverter}, ConverterParameter={resx:Translate AddNew}}"/> 

あなたはコンバータ

public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
{ 
    return parameter.ToString().ToUpper(); 
} 

ConverterParameterが機能しない場合に変換された文字列にアクセスすることができるはずその方法:

Text="{Binding {resx:Translate AddNew}, Converter={StaticResource UpperCaseConverter}}" 

答えて

0

答えは正しいですが、私はここでより良い解決策を見つけました。 IMarkupExtension継承クラスで定義されているパブリックプロパティは、バインド可能であることは明らかです。 xamarin doc

のサンプルを参照するので、私はちょうど

public bool IsUpper { get; set; } = false; 

と私のTranslationExtensionクラスを拡張して、単に私が大文字である必要が今までどこことをバインドさ。私はこれが同じ解決策を探している人に役立つことを願っています。

<Button Image="ic_add.png" Text="{resx:Translate AddNew}" 
Command="{Binding AddNew, IsUpper=true}" HorizontalOptions="FillAndExpand"/> 
3

あなたはこのような何かを試みることができますあなたはただキーを使用して、変換されたリソースをコンバータの中で得ることができます。

関連する問題