WPF FAQ - Type Converters

Find answers for the most frequently asked questions
Expand All Collapse All

Custom classes can be defined in the Window.Resoures of the XAML page. This can be done with the following code snippets.

[XAML]

<Window.Resources>
    <local:BoolToVisibilityConverter x:Key="BoolToVisConverter"/>
</Window.Resources>
<Grid>
    <Button Visibility="{Binding IsVisible,Converter={StaticResource BoolToVisConverter}}"/>
</Grid>
Permalink

In order for your custom type converter to be used as the acting type converter for a custom class, you must apply the .NET Framework “TypeConverter” attribute to your class definition. The Converter Type ’Name’ that you specify through the attribute must be the type name of your custom type converter. With this attribute applied, when an XAML processor handles values where the property type uses your custom class type, it can input strings and return object instances.

You can also provide a type converter on a per-property basis. Instead of applying a .NET Framework “TypeConverter” attribute to the class definition, apply it to a property definition (the main definition, not the get / set implementations within it). The type of the property must match the type that is processed by your custom type converter. With this attribute applied, when an XAML processor handles values of that property, it can process input strings and return object instances. The per-property type converter technique is particularly useful if you choose to use a property type from Microsoft .NET Framework or from some other library where you cannot control the class definition and cannot apply a “TypeConverter” attribute there.

Permalink

Share with

Couldn't find the FAQs you're looking for?

Please submit your question and answer.