gpt4 book ai didi

c# - 自定义本地化 BooleanConverter

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:10 34 4
gpt4 key购买 nike

我正在尝试实现本地化的 BooleanConverter。到目前为止一切正常,但是当您双击属性时,将显示下一条消息:

“‘System.String’类型的对象无法转换为‘System.Boolean’类型。”

我想问题出在具有该 bool 属性的 TypeConverter 的 CreateInstance 方法中。

public class BoolTypeConverter : BooleanConverter
{
private readonly string[] values = { Resources.BoolTypeConverter_False, Resources.BoolTypeConverter_True };

public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string) && value != null)
{
var valueType = value.GetType();

if (valueType == typeof(bool))
{
return values[(bool)value ? 1 : 0];
}
else if (valueType == typeof(string))
{
return value;
}
}

return base.ConvertTo(context, culture, value, destinationType);
}

public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var stringValue = value as string;

if (stringValue != null)
{
if (values[0] == stringValue)
{
return true;
}
if (values[1] == stringValue)
{
return false;
}
}

return base.ConvertFrom(context, culture, value);
}

public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(values);
}
}

最佳答案

你代码的主要问题是你重写了GetStandardValues不正确。

事实上,您不需要重写 GetStandardValues,只需将其删除即可获得预期结果,它在显示所需字符串时就像原始 bool 转换器一样:

enter image description here

当重写 GetStandardValues 时,您应该返回您正在为其创建转换器的类型的支持值列表,然后使用 ConvertTo 提供字符串表示值并使用 ConvertFrom,提供一种从字符串值转换类型的方法。

关于c# - 自定义本地化 BooleanConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34160766/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com