[英]Using BoolToObjectConverter with TranslateExtension True/FalseObject does not return translated string
I am using the BoolToObjectConverter
from Xamarin Community Toolkit (XCT) in my XAML file.我在我的BoolToObjectConverter
文件中使用来自 Xamarin 社区工具包 (XCT) 的 BoolToObjectConverter。 The TrueObject
and FalseObject
properties are set to translatable strings where I use the TranslateExtension
from XCT: TrueObject
和FalseObject
属性设置为可翻译字符串,我使用 XCT 中的TranslateExtension
:
xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
...
<xct:BoolToObjectConverter x:Key="Converter" TrueObject="{xct:Translate YesAnswer}" FalseObject="{xct:Translate NoAnswer}" />
...
<Label Text="{Binding Foo, Converter={StaticResource Converter}}" />
I would have expected that the Label
text would have been the translated yes or no answer.我原以为Label
文本会是翻译的是或否的答案。
Unfortunately the actual Label
output is不幸的是,实际的Label
output 是
Xamarin.Forms.Binding Xamarin.Forms.绑定
The issue could be solved by not using a converter but instead using a DataTrigger
to set the Label.Text
depending on the value of Foo
.该问题可以通过不使用转换器而是使用DataTrigger
根据Foo
的值设置Label.Text
来解决。 However, this clutters the XAML code;但是,这会使 XAML 代码混乱; I would like to stick to using the BoolToObjectConverter
.我想坚持使用BoolToObjectConverter
。 What can I do to obtain the translated string output instead of just the Binding
type?如何获取翻译后的字符串 output 而不仅仅是Binding
类型?
EDIT编辑
Alternatively, I could add x:TypeArguments="BindingBase"
in the converter definition, since this is the return type of the TranslateExtension.ProvideValue
method, but this does not make any difference to the output result.或者,我可以在转换器定义中添加x:TypeArguments="BindingBase"
,因为这是TranslateExtension.ProvideValue
方法的返回类型,但这对 output 结果没有任何影响。
The best solution I could come up with was to subclass XCT TranslateExtension
and implement IMarkupExtension
for a string
return value.我能想出的最佳解决方案是将 XCT TranslateExtension
子类化并为string
返回值实现IMarkupExtension
。 This way I could use the subclass to obtain translated strings in the converter.这样我就可以使用子类在转换器中获取翻译后的字符串。
Implementation执行
public class TranslateToStringExtension : Xamarin.CommunityToolkit.Extensions.TranslateExtension, IMarkupExtension<string>
{
public new string ProvideValue(IServiceProvider serviceProvider)
{
var binding = base.ProvideValue(serviceProvider) as Binding;
string path;
var value = string.IsNullOrEmpty(path = binding?.Path?.Trim('[', ']'))
? null
: LocalizationResourceManager.Current.GetValue(path);
return value;
}
}
Usage用法
<xct:BoolToObjectConverter
x:Key="Converter"
TrueObject="{local:TranslateToString YesAnswer}"
FalseObject="{local:TranslateToString NoAnswer}" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.