GridView中的GridViewComboBoxColumn列,如果需要使用TypeConverter将非字符串类型的数据源转换为字符串进行展示,可按如下几步进行:
例如,数据源为如下枚举类型:
public enum MyColor
{
Red,
Yellow,
Green
}
- 展示的时候,需要转换为汉字,先定义如下类型,作为GridViewComboBoxColumn的数据源:
public class MyColorItem
{
public MyColor Value { get; set; }
public string Description { get; set; }
}
- 创建转换器:
public class MyColorToStringConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if(sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string color)
{
switch (color)
{
case "红":
return MyColor.Red;
case "黄":
return MyColor.Yellow;
case "绿":
return MyColor.Green;
default:
break;
}
}
return base.ConvertFrom(context, culture, value);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (value is MyColor color)
{
switch (color)
{
case MyColor.Red:
return "红";
case MyColor.Yellow:
return "黄";
case MyColor.Green:
return "绿";
default:
break;
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
- 初始化时设置GridViewComboBoxColumn列的相关属性:
List<MyColorItem> MyColorItemSource = new List<CheckTypeItem>
{
new MyColorItem{ Value = MyColor.Red, Description = "红" },
new MyColorItem{ Value = MyColor.Yellow Description = "黄" },
new MyColorItem{ Value = MyColor.Green, Description = "绿" }
};
var column = radGridView.Columns["MyColor"] as GridViewComboBoxColumn;
if (column != null)
{
column.DataSource = MyColorItemSource;
column.ValueMember = "Value";
column.DisplayMember = "Description";
column.DataTypeConverter = new MyColorToStringConverter();
}
需要注意的是,如果不定义步骤1中的MyColorItem类型,直接使用List<string>{"红", "黄", "绿"}
作为GridViewComboBoxColumn列的DataSource,转换器会报错。