c# - 如何在 xamarin.forms 中的 xaml 中大写/小写 resx 绑定(bind)?

标签 c# xamarin xamarin.forms resx

正在关注 xamarin localization topic和 sample TodoLocalized ,我使我的应用程序多语言。我的问题是有时,我有时需要使用大写的单词,我不想在 resx 文件中创建另一个翻译作为同一个单词的大写版本。实现这一目标的最佳方法是什么?如果可能扩展此翻译扩展名?还是应该使用 IValueConvertor?如果是,如何在 xaml 中绑定(bind)它

    // 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"/>

我试过这样做,但我猜 Binding 需要一个在 BindingContext 中定义的属性。因此它不起作用,但我如何为 resx 文件中定义的文本实现它。

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

最佳答案

你可以尝试这样的事情:

<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 不起作用,您可以只使用 key 并在转换器中获取已翻译的资源。

关于c# - 如何在 xamarin.forms 中的 xaml 中大写/小写 resx 绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42762832/

相关文章:

c# - Xamarin.Forms 如何使按钮显示在一行中

c# - .NET 中的点有多贵?

c# - 无法加载文件或程序集 'CsvHelper'(C#、VS2019、CSVHelper)

c# - xamarin 表单中的异步 Task<T> 问题

android - Xamarin ContentPage BackgroundImage属性在Android上使应用程序崩溃

c# - 如何在 xamarin.forms 中读取图像源或图像名称?

c# - XAML 数据绑定(bind)在未设置 Viewmodel 时覆盖属性

c# - 在 Xamarin Forms 中添加值后 ListView 不刷新

c# - 在 C# 中延迟发送电子邮件

需要 C# 正则表达式