1

Suppose that I have a property MyProperty of type MyType in a class MyClass. I want to use XAML to assign it some complex value of another type (let's take String, for example). So, I create MyTypeConverter which can convert from String to MyType and apply [TypeConverter(typeof(MyTypeConverter))] to the MyClass class.

The following code works fine (i.e. invokes MyTypeConverter.ConvertFrom):

<MyClass.MyProperty>
    text
</MyClass.MyProperty>

But as soon as I change the property value to a XAML elemet, the TypeConverter is no longer being invoked which results in a conversion exception.

<MyClass.Property>
    <sys:String>text</sys:String>
</MyClass.Property>

How can I implement conversion for the values defined as XAML elements?

Ark-kun
  • 6,358
  • 2
  • 34
  • 70
  • This behaviour seems absolutely logical to me, you cannot *explicitly* assign a string object to a property of a different type. – H.B. Jul 03 '12 at 00:59
  • `TypeConverter` can convert and is used to convert from any type. Why should it be restrained to conversion from string literals only (and bindings)? – Ark-kun Jul 03 '12 at 01:04
  • What I want is to not need to explicitly wrap the XAML elements in adapters every time. – Ark-kun Jul 03 '12 at 01:10
  • For literals and bindings the type is not explicitly set. Type conversion is implicit so it makes sense that it only applies to implciitly typed values without overriding explicit ones. (Also one usually only converts from and to strings, so haivng this limitation should not really matter) – H.B. Jul 03 '12 at 01:12
  • Ok. I looked at the TypeConverter implementations and they really only deal with strings. I wonder why did they decided to create and use the powerful TypeConverter system with all its CanConvertFrom/CanConvertTo, when all that they actually needed and used was a pair of FromString/ToString methods (Serialize/Deserialize). BTW, the implicit conversion operators don't work too. Looks like I've hit the dead end. – Ark-kun Jul 03 '12 at 01:24
  • I thought/you said the first snippet worked? – H.B. Jul 03 '12 at 01:54
  • The snuppets are simplified. My real values are complex types. I just wanted to avoid wrapping each collection value in a converter: `` – Ark-kun Jul 03 '12 at 02:35

0 Answers0