Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between TypeConverters and MarkupExtension in WPF

Tags:

wpf

xaml

What is the difference between TypeConverters and MarkupExtension ?

like image 572
VirgoGuy Avatar asked Jul 05 '11 13:07

VirgoGuy


2 Answers

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

<Button Background="Red" />

MarkupExtension allow you to provide more customized values to properties. There are also a few special markup extensions, Binding, MultiBinding, and DynamicResource. These do more than just provide a static value, and instead provide a more dynamic value.

So you could build markup extensions that perform the same operations as type converters, but then you would have to explicitly use them, versus the implicit nature of type converters.

like image 127
CodeNaked Avatar answered Sep 22 '22 07:09

CodeNaked


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

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

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

<Button Background="Red" />

...this is much quicker to write and understand. However, the TypeConverter is ALWAYS called for the property assignment and you cannot prevent the XAML from causing the TypeConverter to be called.

A MarkupExtension is used to return an object that is then assigned to the specified property. This is more flexible because you can decide when and where to use a MarkupExtension and you are not restriced to particular properties that have been marked in advance with an attribute. Examples of markup extesions are Binding, StaticResource and DynamicResource.

So the type converter is great for specific properties of a specific type that you want to accept a greater range of values than the type itself defines. The markup extension is great for more general purpose use where the developer decides when and where to use it

like image 20
Phil Wright Avatar answered Sep 22 '22 07:09

Phil Wright