Hello Hugues,
Thank you for writing.
If I understand your requirement correctly, you are trying to create an
ExpandableObjectConverter and assign it to a specific property at run time. For this purpose, you can use the following code snippet:
public
Form1()
{
InitializeComponent();
PropertyDescriptor prop = TypeDescriptor.GetProperties(
typeof
(Item))[
"Cell"
];
TypeConverter tc = prop.Converter;
typeof
(PropertyDescriptor).GetField(
"converter"
, BindingFlags.NonPublic
| BindingFlags.Instance).SetValue(prop,
new
MyConverter());
this
.radPropertyGrid1.SelectedObject =
new
Item(123,
new
Cell(3.7m,4.2m),
"test"
);
}
public
class
Item
{
public
int
Id {
get
;
set
; }
public
Cell Cell {
get
;
set
; }
public
string
Title {
get
;
set
; }
public
Item(
int
id, Cell cell,
string
title)
{
this
.Id = id;
this
.Cell = cell;
this
.Title = title;
}
}
public
class
Cell
{
public
decimal
X {
get
;
set
; }
public
decimal
Y {
get
;
set
; }
public
Cell(
decimal
x,
decimal
y)
{
this
.X = x;
this
.Y = y;
}
}
public
class
MyConverter:ExpandableObjectConverter
{
public
override
bool
CanConvertTo(ITypeDescriptorContext context,
System.Type destinationType)
{
if
(destinationType ==
typeof
(
string
))
return
true
;
return
base
.CanConvertTo(context, destinationType);
}
public
override
object
ConvertTo(ITypeDescriptorContext context,
CultureInfo culture,
object
value,
System.Type destinationType)
{
Cell cell = value
as
Cell;
if
(destinationType ==
typeof
(System.String) &&
value !=
null
)
{
return
(
"X: "
+ cell.X +
" Y: "
+ cell.Y);
}
return
base
.ConvertTo(context, culture, value, destinationType);
}
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)
{
string
[] tokens = (value +
""
).Split(
new
string
[] {
"X: "
,
"Y: "
}, StringSplitOptions.RemoveEmptyEntries) ;
if
(tokens.Length == 2)
{
decimal
x;
decimal
y;
if
(
decimal
.TryParse(tokens[0],
out
x) &&
decimal
.TryParse(tokens[1],
out
y))
{
return
new
Cell(x,y);
}
}
return
base
.ConvertFrom(context, culture, value);
}
}
If it is not the exact case, I would kindly ask you to provide a more detailed explanation about the behavior that you are trying to achieve. Thank you in advance.
I hope this information helps. Should you have further questions, I would be glad to help.
Regards,
Desislava
Telerik
Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.