正在关注 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/