What is the difference between TypeConverters and MarkupExtension in WPF

What is the difference between TypeConverters and MarkupExtension ?

+7
source share
2 answers

TypeConverters are used to implicitly convert one type to another. For example, BrushConverter can convert the string "Red" to SolidColorBrush, whose color property is set to red. As in this case:

 <Button Background="Red" /> 

MarkupExtension allows you to provide more custom values ​​to properties. There are also several special markup extensions, Binding, MultiBinding, and DynamicResource. They not only provide a static value, but also provide a more dynamic value.

So, you can create markup extensions that perform the same operations as type converters, but then you will have to use them explicitly compared to the implicit nature of type converters.

+7
source

A TypeConverter is designed to convert from one type to another. There are several provided out of the box such as BrushConverter, ColorConverter, BooleanConverter and so on. See here for a complete list. What distinguishes type converters is that they can be applied to a property definition using the following atttribute definition in a class definition ...

 [TypeConverterAttribute(typeof(BrushConverter)] public Brush Background { ... } 

... the BrushConverter implementation knows that if it receives a string as input, it should try and convert it to a known instance of SolidBrush. This means that your XAML does not need to assign the actual SolidBrushes.Red link to the property, but instead use a simple string ...

 <Button Background="Red" /> 

... it's much faster to write and understand. However, TypeConverter has ALWAYS called a property assignment, and you cannot prevent XAML from invoking TypeConverter.

A MarkupExtension is used to return an object, which is then assigned to the specified property. This is more flexible because you can decide when and where to use MarkupExtension, and you are not limited to specific properties that have been pre-tagged with an attribute. Examples of markup extensions are binding, StaticResource, and DynamicResource.

Thus, a type converter is great for specific properties of a particular type that you want to accept a wider range of values ​​than the type itself. The markup extension is great for more general use when the developer decides when and where to use it.

+1
source

Source: https://habr.com/ru/post/892033/


All Articles