Compartilhar via


TypeConverters and XAML

The TypeConverter class serves a particular purpose as part of the implementation for a managed custom class that can be used as a property value in Extensible Application Markup Language (XAML) attribute usage. If you write a custom class, and you want instances of your class to be usable as Extensible Application Markup Language (XAML) settable attribute values, you might need to apply a TypeConverterAttribute to your class, write a custom TypeConverter class, or both.

Este tópico contém as seguintes seções.

  • XAML and String Values
  • Implementing a Type Converter
  • Applying the TypeConverterAttribute
  • Tópicos relacionados

XAML and String Values

When you set an attribute value in XAML, the initial type of that value is String. Even other primitives such as Double are initially strings to a XAML processor, although the conversion to other nonstring primitive values or from named values of an enumeration is relatively straightforward because of built-in type conversions.

A XAML processor needs two pieces of information in order to process an attribute value. The first piece of information is the value type of the property that is being set. Any string that defines an attribute value and that is processed in XAML must ultimately be converted or resolved to a value of that type. If the value is a primitive, a direct conversion of the string is attempted. If the value is an enumeration, the string is used to check for a name match in that enumeration. If the value is neither a primitive or an enumeration, then the type in question must be able to provide an instance of the type, or a value, based on a converted string.

A special case is a markup extension. Markup extension usages must be handled by a XAML processor prior to checking for property type and other considerations. Em geral, o propósito de uma extensão de marcação é uma seqüência de caracteres de processo e retornar um objeto. If the object returned is a type match for the property, the markup extension supplies a value for a property in a manner that avoids any type conversion taking place outside of the markup extension implementation code. One common situation where a markup extension is necessary is to make a reference to an object that already exists (at best, a stateless type converter could only generate a new instance, which might not be desirable). For more information on markup extensions, see Extensão de Marcação e XAML.

TypeConverter

Se o valor não é um tipo primitivo ou enumeração e não sem uso de extensão de marcação, em seguida, deve haver algum meio de converter um String o valor apropriado ou uma nova instância quando XAML é processada. Essa é a função do TypeConverter implementação. TypeConverter define quatro membros que são relevantes para a conversão para e de seqüências de caracteres para XAML Processando finalidades:

Of these, the most important method is ConvertFrom. This method converts the input string to the required object type.

The next most important method is ConvertTo. If a WPF application is converted to a markup representation (for instance, if it is saved to XAML), ConvertTo is responsible for producing a markup representation.

CanConvertTo and CanConvertFrom are support methods that are used when a service queries the capabilities of the TypeConverter implementation. You must implement these methods to return true for certain cases, particularly for the String type.

Implementing a Type Converter

Implementing ConvertFrom

To be usable as a TypeConverter implementation that supports XAML, the ConvertFrom method for that converter must accept a string as the value parameter. Se a seqüência de caracteres era válido Formatar e pode ser convertida por meio de TypeConverter implementação e, em seguida, o objeto retornado deve oferecer suporte a projeção para o tipo esperado pela propriedade. Otherwise, the ConvertFrom implementation must return null.

Each TypeConverter implementation can have its own interpretation of what constitutes a valid string for a conversion, and can also use or ignore the type description or culture contexts passed as parameters. However, the WPF XAML processing might not pass values to the type description context in all cases, and also might not pass culture based on xml-lang.

ObservaçãoObservação:

Não use os caracteres de chave de abertura, particularmente { , sistema autônomo um elemento de seu formato de seqüência de caracteres possível. These characters are reserved as the entry and exit for a markup extension sequence.

Implementing ConvertTo

ConvertTo potencialmente é usado para suporte de serialização. Serialization support for your custom type is not an absolute requirement. However, if you are implementing a control, or using serialization of as part of the features or design of your class, you should implement ConvertTo.

To be usable as a TypeConverter implementation that supports XAML, the ConvertTo method for that converter must accept an instance of the type (or a value) being supported as the value parameter. When the destinationType parameter is type String, then the returned object must castable to String. The returned string must represent a serialized value of value. Ideally, the serialization format you choose should be capable of generating the same value if that string were passed to the ConvertFrom implementation of the same converter, without significant loss of information.

If the value cannot be serialized, or the converter does not support serialization, the ConvertTo implementation must return null, and is permitted to throw an exception in this case.

If destinationType parameter is not of type String, you can choose your own converter handling. Typically, you would revert to base implementation handling.

Each TypeConverter implementation can have its own interpretation of what constitutes a valid string for a conversion, and can also use or ignore the type description or culture contexts passed as parameters.

ObservaçãoObservação:

Não use os caracteres de chave de abertura, particularmente { , sistema autônomo um elemento de seu formato de seqüência de caracteres possível. These characters are reserved as the entry and exit for a markup extension sequence.

Implementing CanConvertTo

Your CanConvertTo implementation should return true for destinationType of type String, and otherwise defer to the base implementation.

Implementing CanConvertFrom

Your CanConvertFrom implementation should return true for sourceType of type String, and otherwise defer to the base implementation.

Applying the TypeConverterAttribute

In order for your custom type converter to be used as the acting type converter for a custom class, you must apply the Atributo do .NET Framework TypeConverterAttribute to your class definition. The ConverterTypeName that you specify through the attribute must be the type name of your custom type converter. With this attribute applied, when a 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 Atributo do .NET Framework TypeConverterAttribute 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 a 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 TypeConverterAttribute there.

Consulte também

Conceitos

XAML Overview

Extensão de Marcação e XAML

Terminologia de sintaxe XAML

Referência

TypeConverter