Xamarin.forms 在Xamarin表单中进行数据绑定时不调用TypeConverter
我正在尝试将枚举绑定到Picker控件,并向用户显示本地化名称。我使用的代码与我的WPF应用程序中的代码完全相同,但由于某些原因,它在Xamarin表单中不起作用,并且它显示enum的命名常量,而不是本地化名称。看起来好像没有调用TypeConverter。 我检查了类型转换器是否按预期工作:Xamarin.forms 在Xamarin表单中进行数据绑定时不调用TypeConverter,xamarin.forms,data-binding,localization,typeconverter,Xamarin.forms,Data Binding,Localization,Typeconverter,我正在尝试将枚举绑定到Picker控件,并向用户显示本地化名称。我使用的代码与我的WPF应用程序中的代码完全相同,但由于某些原因,它在Xamarin表单中不起作用,并且它显示enum的命名常量,而不是本地化名称。看起来好像没有调用TypeConverter。 我检查了类型转换器是否按预期工作:TypeDescriptor.GetConverter(typeof(Country)).ConvertTo(Country.sr,typeof(string))作为字符串返回本地化名称 这是我的类型转换器
TypeDescriptor.GetConverter(typeof(Country)).ConvertTo(Country.sr,typeof(string))作为字符串代码>返回本地化名称
这是我的类型转换器类
公共类EnumDescriptionTypeConverter:EnumConverter
{
公共EnumDescriptionTypeConverter(类型)
:基本(类型)
{
}
公共重写对象转换为(ITypeDescriptorContext上下文,System.Globalization.CultureInfo区域性,对象值,类型destinationType)
{
if(destinationType==typeof(string))
{
if(值!=null)
{
FieldInfo fi=value.GetType().GetField(value.ToString());
如果(fi!=null)
{
var attributes=(DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute),false);
返回((attributes.Length>0)&(!String.IsNullOrEmpty(attributes[0].Description))?属性[0]。说明:value.ToString();
}
}
返回字符串。空;
}
返回base.ConvertTo(上下文、区域性、值、destinationType);
}
}
还有我的DescriptionAttribute类
public class LocalizedDescriptionAttribute : DescriptionAttribute
{
ResourceManager _resourceManager;
readonly string _resourceKey;
public LocalizedDescriptionAttribute(string resourceKey, Type resourceType)
{
_resourceManager = new ResourceManager(resourceType);
_resourceKey = resourceKey;
}
public override string Description
{
get
{
string description = _resourceManager.GetString(_resourceKey);
return string.IsNullOrWhiteSpace(description) ? string.Format("[[{0}]]", _resourceKey) : description;
}
}
}
还有我的枚举
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum Country
{
[LocalizedDescription("sl", typeof(Resource))]
sl,
[LocalizedDescription("sr", typeof(Resource))]
sr,
[LocalizedDescription("th", typeof(Resource))]
th
}
在表单中,使用可以引用这个。但是为什么TypeConverter不能工作呢?我有一个大项目,更换类型转换器需要很多努力。我知道IValueConverter可以工作,但我希望避免源代码重构,因为这需要很多努力。通常,IValueConverter
在Xamarin表单中使用,然后建议您尝试一下。稍后我将尝试使用TypeConverter
,如果解决方案将在此处更新的话。