
An NotSupportedException is thrown if the example object is null or is not a Color.
#Colorconverter canconvertfrom example code#
And of course have the required code to convert from an int to a bool in the ConvertFrom() method. public override object ConvertFrom(ITypeDescriptorContext td, System. It will have to recognize typeof(int) explicitly. This converter can be used both within bindings and in code-behind to give more concise property setters. The diagnostic for a false return in your code snippet is that you simply didn't implement CanConvertFrom() correctly. This post provides a simple IValueConverter implementation that makes use of the framework type converters in order to convert between a large range of source / target types. It just isn't that clear that you'll run into a practical use-case, unless you write the code to use the TypeConverter explicitly. You can certainly make a custom TypeConverter do anything you want. These are the top rated real world C (CSharp) examples of .ConvertFrom extracted from. Which is all they ever have to do when a Point or Color is displayed in a PropertyGrid or the built-in Property Window. And a matching ConvertFrom() method that only has the code to parse the string. Their CanConvertFrom() methods only say "go ahead" if the sourceType argument is System.String. The Framework has lots of built-in TypeConverters. A string that you look at in the designer and you can edit to change the object. With their principal role to convert back and forth between an object of a specific type and a string. They are glue that make the various designers in Visual Studio work. It is pretty important to understand why type converters exist. Other question: if MyTypeConverter CanConvertFrom(typeof(X)) and MyTypeConverter CanConvertTo(typeof(Y), should MyTypeConverter be able to convert from type X to type Y? So it has nothing to do with value types or reference types. But apparently a string CanConvertTo a string, but a can't be converted to by the ColorConverter. Long and RGB are related they are just different ways of calculating the same number. As an example: Where Red: 33, Green: 115 and Blue: 70. I see similar behaviour if I want to convert an to a using PointConverter. CanConvertFrom(Type) When implemented in a derived class, returns a Boolean value that indicates whether or not the derived type converter can convert sourceType to its target type. Long Blue x 256 x 256 + Green x 256 + Red. TypeConverter typeConverter = new TypeConverter() īool b = typeConverter.CanConvertTo(typeof(int))ī appears to equal false.

I see that Micosoft has some inconsistent behaviour: int i = 4 Should M圜lassConverter be able to convert objects of Type M圜lass?Īnd if so, If M圜lassConverter is asked to convert an object of M圜lass to an object of M圜lass, should it return the original M圜lass or a copy of it? Public override bool CanConvertFrom(Type destType) Suppose I have a M圜lass that has a TypeConverter
