XAML 類型轉換子概觀Type Converters for XAML Overview

物件寫入器的類型轉換器供應邏輯,可將 XAML 標記中的字串轉換為物件圖形中的特定物件。Type converters supply logic for an object writer that converts from a string in XAML markup into particular objects in an object graph. 在 .NET Framework XAML 服務中,類型轉換器必須是衍生自 TypeConverter的類別。In .NET Framework XAML Services, the type converter must be a class that derives from TypeConverter. 有些轉換器也支援 XAML 儲存路徑,而且可用來將序列化標記中的物件序列化成字串格式。Some converters also support the XAML save path and can be used to serialize an object into a string form in serialization markup. 本主題描述如何以及何時叫用 XAML 中的類型轉換器,並提供 TypeConverter之方法覆寫的實作建議。This topic describes how and when type converters in XAML are invoked, and provides implementation advice for the method overrides of TypeConverter.

類型轉換概念Type Conversion Concepts

下列各節說明下列作業的基本概念:XAML 如何使用字串,以及 .NET Framework XAML 服務中的物件寫入器如何使用類型轉換器來處理在 XAML 原始碼中發現的一些字串值。The following sections explain basic concepts about how XAML uses strings, and how object writers in .NET Framework XAML Services use type converters to process some of the string values that are encountered in a XAML source.

XAML 和字串值XAML and String Values

在 XAML 檔案中設定屬性值時,該值的初始類型是一般感應器中的字串,以及 XML 感應器中的字串屬性值。When you set an attribute value in a XAML file, the initial type of that value is a string in a general sense, and a string attribute value in an XML sense. 甚至,其他基本類型 (例如 Double ) 一開始是 XAML 處理器的字串。Even other primitives such as Double are initially strings to a XAML processor.

在大部分情況下,XAML 處理器需要兩項資訊才能處理屬性值。In most cases, a XAML processor needs two pieces of information to process an attribute value. 第一項資訊是正在設定之屬性的實值類型。The first piece of information is the value type of the property that is being set. 任何定義屬性值並在 XAML 中處理的字串最後必須轉換或解析成該類型的值。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. 如果值是 XAML 剖析器可理解的基本類型 (例如數值),則會嘗試直接轉換字串。If the value is a primitive that is understood by the XAML parser (such as a numeric value), a direct conversion of the string is attempted. 如果屬性的值參考列舉,則會檢查提供的字串是否有該列舉中具名常數的名稱相符項。If the value for the attribute references an enumeration, the supplied string is checked for a name match to a named constant in that enumeration. 如果值不是剖析器理解的基本類型也不是列舉中的常數名稱,則適用的類型必須可以提供以已轉換字串為基礎的值或參考。If the value is neither a parser-understood primitive nor a constant name from an enumeration, the applicable type must be able to provide a value or reference that is based on a converted string.

注意

XAML 語言指示詞不會使用類型轉換器。XAML language directives do not use type converters.

類型轉換器和標記延伸Type Converters and Markup Extensions

XAML 處理器必須先處理標記延伸使用方式,才會檢查屬性類型和其他考量。Markup extension usages must be handled by a XAML processor before it checks for property type and other considerations. 例如,如果設為屬性 (Attribute) 的屬性 (Property) 通常具有類型轉換,但在特定情況下是由標記延伸使用方式所設定,則會先處理標記延伸行為。For example, if a property being set as an attribute normally has a type conversion, but in a particular case is set by a markup extension usage, then the markup extension behavior processes first. 需要有標記延伸的一個常見情況是參考現有的物件。One common situation where a markup extension is necessary is to make a reference to an object that already exists. 在此案例中,無狀態類型轉換器只能產生新的執行個體,但這可能不是令人滿意的情況。For this scenario, a stateless type converter can only generate a new instance, which might not be desirable. 如需標記延伸的詳細資訊,請參閱 Markup Extensions for XAML OverviewFor more information about markup extensions, see Markup Extensions for XAML Overview.

原生類型轉換器Native Type Converters

在 WPF 和 .NET XAML 服務的執行中, 有某些 CLR 型別具有原生類型轉換處理, 不過, 這些 CLR 型別並不是以傳統方式視為基本類型。In the WPF and .NET XAML services implementations, there are certain CLR types that have native type conversion handling, however, those CLR types are not conventionally thought of as primitives. 這類類型的範例是 DateTimeAn example of such a type is DateTime. 其中一個原因是 .NET Framework 架構的運作方式:類型 DateTime 定義於 mscorlib (.NET 中的最基本程式庫)。One reason for this is how the .NET Framework architecture works: the type DateTime is defined in mscorlib, the most basic library in .NET. DateTime 不允許使用來自另一個引進相依性的組件進行屬性設定 (TypeConverterAttribute 來自系統);因此,無法支援透過屬性設定的一般類型轉換器探索機制。DateTime is not permitted to be attributed with an attribute that comes from another assembly that introduces a dependency (TypeConverterAttribute is from System); therefore, the usual type converter discovery mechanism by attributing cannot be supported. 而是,XAML 剖析器都有一份需要原生處理的類型清單,而且這些類型的處理方式與 true 基本類型的處理方式類似。Instead, the XAML parser has a list of types that need native processing, and it processes these types similar to how the true primitives are processed. 如果是 DateTime則此處理包含 Parse呼叫。In the case of DateTime, this processing involves a call to Parse.

實作類型轉換器Implementing a Type Converter

下列章節討論 TypeConverter 類別的 API。The following sections discuss the API of the TypeConverter class.

TypeConverterTypeConverter

在 .NET Framework XAML 服務下,用於 XAML 用途的所有類型轉換器是衍生自基底類別 TypeConverter的類別。Under .NET Framework XAML Services, all type converters that are used for XAML purposes are classes that derive from the base class TypeConverter. TypeConverter 類別要先存在於 .NET Framework 版本中,XAML 才會存在;其中一個原始 TypeConverter 案例是提供視覺化設計工具中屬性編輯器的字串轉換。The TypeConverter class existed in versions of the .NET Framework before XAML existed; one of the original TypeConverter scenarios was to provide string conversion for property editors in visual designers.

針對 XAML,會展開 TypeConverter 的角色。For XAML, the role of TypeConverter is expanded. 基於 XAML, TypeConverter 是支援特定目標字串與來源字串轉換的基底類別。For XAML purposes, TypeConverter is the base class for providing support for certain to-string and from-string conversions. 來源字串會從 XAML 剖析字串屬性值。From-string enables parsing a string attribute value from XAML. 目標字串可能會讓特定物件屬性的執行階段值處理回 XAML 中的屬性,以進行序列化。To-string might enable processing a run-time value of a particular object property back into an attribute in XAML for serialization.

TypeConverter 定義四個成員,而這些成員與基於 XAML 處理轉換目標字串和來源字串有關:TypeConverter defines four members that are relevant for converting to-string and from-string for XAML processing purposes:

在這些成員中,最重要的方法是 ConvertFrom,可將輸入字串轉換成所需的物件類型。Of these members, the most important method is ConvertFrom, which converts the input string to the required object type. ConvertFrom 方法可以實作以將更廣泛範圍的類型轉換為轉換器的預定目的地類型。The ConvertFrom method can be implemented to convert a wider range of types into the intended destination type of the converter. 因此,它可以提供不僅 XAML 的用途,例如支援執行階段轉換。Therefore, it can serve purposes that extend beyond XAML, such as supporting run-time conversions. 不過,對於 XAML 使用,只有可處理 String 輸入的程式碼路徑才重要。However, for XAML use, only the code path that can process a String input is important.

第二個最重要的方法是 ConvertToThe second most important method is ConvertTo. 如果應用程式轉換成標記呈現 (例如,如果儲存為 XAML 檔案), ConvertTo 會包含在 XAML 文字寫入器的較大案例中,而 XAML 文字寫入器會產生標記呈現。If an application is converted to a markup representation (for example, if it is saved to XAML as a file), ConvertTo is involved in the larger scenario of a XAML text writers produce a markup representation. 在此情況下,XAML 的重要程式碼路徑是呼叫端通過 destinationTypeString時。In this case, the important code path for XAML is when the caller passes a destinationType of String.

CanConvertToCanConvertFrom 是服務查詢 TypeConverter 實作之功能時所使用的支援方法。CanConvertTo and CanConvertFrom are support methods that are used when a service queries the capabilities of the TypeConverter implementation. 您必須實作這些方法來傳回轉換器對等轉換方法所支援類型特有案例的 trueYou must implement these methods to return true for type-specific cases that the equivalent conversion methods of your converter support. 基於 XAML,這通常表示 String 類型。For XAML purposes, this generally means the String type.

XAML 的文化特性資訊和類型轉換器Culture Information and Type Converters for XAML

每個 TypeConverter 實作都可以唯一解譯轉換的有效字串,也可以使用或忽略傳遞為參數的類型描述。Each TypeConverter implementation can uniquely interpret what is a valid string for a conversion, and it can also use or ignore the type description that is passed as parameters. 文化特性和 XAML 類型轉換的重要考量如下:雖然 XAML 支援使用可當地語系化字串做為屬性值,但是您無法使用這些可當地語系化字串做為具有特定文化特性需求的類型轉換器輸入。An important consideration for culture and XAML type conversion is the following: although using localizable strings as attribute values is supported by XAML, you cannot use these localizable strings as type converter input with specific culture requirements. 這項限制是因為 XAML 屬性值的類型轉換器包含使用 en-US 文化特性的必要固定語言 XAML 處理行為。This limitation is because type converters for XAML attribute values involve a necessarily fixed-language XAML-processing behavior that uses en-US culture. 如需這種限制之設計原因的詳細資訊, 請參閱 XAML 語言規格 ( [MS-]xaml) 或WPF 全球化和當地語系化總覽For more information about the design reasons for this restriction, see the XAML language specification ([MS-XAML]) or WPF Globalization and Localization Overview.

在文化特性可能是問題的範例中,某些文化特性會使用逗號 (而非句號) 做為字串形式中數字的小數點分隔符號。As an example where culture can be an issue, some cultures use a comma instead of a period as the decimal point delimiter for numbers in string form. 這項使用與許多現有類型轉換器的行為衝突,後者是使用逗號做為分隔符號。This use collides with the behavior that many existing type converters have, which is to use a comma as a delimiter. 在周圍 XAML 中透過 xml:lang 傳遞文化特性並不能解決問題。Passing a culture through xml:lang in the surrounding XAML does not solve the issue.

實作 ConvertFromImplementing ConvertFrom

若要可做為支援 XAML 的 TypeConverter 實作來重複使用,該轉換器的 ConvertFrom 方法必須接受字串做為 value 參數。To be usable as a TypeConverter implementation that supports XAML, the ConvertFrom method for that converter must accept a string as the value parameter. 如果字串的格式有效,而且可以透過 TypeConverter 實作進行轉換,則傳回的物件必須支援轉型為屬性所預期的類型。If the string is in a valid format and can be converted by the TypeConverter implementation, the returned object must support a cast to the type that is expected by the property. 否則, ConvertFrom 實作必須傳回 nullOtherwise, the ConvertFrom implementation must return null.

每個 TypeConverter 實作都可以唯一解譯什麼可替代轉換的有效字串,也可以使用或忽略傳遞為參數的類型描述或文化特性內容。Each TypeConverter implementation can uniquely interpret what constitutes a valid string for a conversion, and it can also use or ignore the type description or culture contexts that are passed as parameters. 不過,WPF XAML 處理可能不會在所有情況下都將值傳遞至類型描述內容,也可能不會根據 xml:lang來傳遞文化特性。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.

注意

請勿使用大括弧 ({}), 特別是左大括弧 ({), 做為字串格式的元素。Do not use the braces ({}), specifically the opening brace ({), as an element of your string format. 這些字元保留做為標記延伸序列的進入及結束。These characters are reserved as the entry and exit for a markup extension sequence.

如果類型轉換器必須可以從 .NET Framework XAML 服務物件寫入器存取 XAML 服務,但針對內容進行的 GetService 呼叫未傳回該服務,則會適當地擲回例外狀況。It is appropriate to throw an exception when your type converter must have access to a XAML service from the .NET Framework XAML Services object writer, but the GetService call that is made against the context does not return that service.

實作 ConvertToImplementing ConvertTo

ConvertTo 可能用於序列化支援。ConvertTo is potentially used for serialization support. 透過自訂類型和其類型轉換器之 ConvertTo 的序列化支援不是絕對需求。Serialization support through ConvertTo for your custom type and its type converter is not an absolute requirement. 不過,如果您正在實作控制項,或使用功能某部分的序列化或類別設計,則應該實作 ConvertToHowever, if you are implementing a control, or using serialization of as part of the features or design of your class, you should implement ConvertTo.

若要可做為支援 XAML 的 TypeConverter 實作來重複使用,該轉換器的 ConvertTo 方法必須接受所支援類型 (或值) 的執行個體做為 value 參數。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) that is supported as the value parameter. destinationType 參數的類型是 String時,傳回的物件必須可以轉型為 StringWhen the destinationType parameter is of type String, the returned object must be able to be cast as String. 傳回的字串必須代表 value 的序列化值。The returned string must represent a serialized value of value. 理想上,您選擇的序列化格式應該可以產生相同的值,就像將該字串傳遞給相同轉換器的 ConvertFrom 實作,而不會明顯遺失資訊。Ideally, the serialization format that you choose should be able to generate the same value as if that string were passed to the ConvertFrom implementation of the same converter, without significant loss of information.

如果無法序列化值,或轉換器不支援序列化,則 ConvertTo 實作必須傳回 null 並可能會擲回例外狀況。If the value cannot be serialized or the converter does not support serialization, the ConvertTo implementation must return null and can throw an exception. 不過,如果您確實擲回例外狀況,則應該報告無法使用該轉換做為 CanConvertTo 實作的一部分;因此,支援先使用 CanConvertTo 檢查以避免例外狀況的最佳做法。However, if you do throw exceptions, you should report the inability to use that conversion as part of your CanConvertTo implementation so that the best practice of checking with CanConvertTo first to avoid exceptions is supported.

如果 destinationType 參數的類型不是 String,則可以選擇專屬轉換器處理。If the destinationType parameter is not of type String, you can choose your own converter handling. 一般而言,您會回復成基底實作處理,而在基底 ConvertTo 中會引發特定例外狀況。Typically, you revert to base implementation handling, which in the base ConvertTo raises a specific exception.

如果類型轉換器必須可以從 .NET Framework XAML 服務物件寫入器存取 XAML 服務,但針對內容進行的 GetService 呼叫未傳回該服務,則會適當地擲回例外狀況。It is appropriate to throw an exception when your type converter must have access to a XAML service from the .NET Framework XAML Services object writer, but the GetService call that is made against the context does not return that service.

實作 CanConvertFromImplementing CanConvertFrom

您的 CanConvertFrom 實作應該傳回類型 truesourceTypeString ,否則會進行基底實作。Your CanConvertFrom implementation should return true for sourceType of type String and otherwise, defer to the base implementation. 不會從 CanConvertFrom擲回例外狀況。Do not throw exceptions from CanConvertFrom.

實作 CanConvertToImplementing CanConvertTo

您的 CanConvertTo 實作應該傳回類型 truedestinationTypeString,否則會進行基底實作。Your CanConvertTo implementation should return true for destinationType of type String, and otherwise defer to the base implementation. 不會從 CanConvertTo擲回例外狀況。Do not throw exceptions from CanConvertTo.

套用 TypeConverterAttributeApplying the TypeConverterAttribute

若要藉由 .NET Framework XAML 服務, 將您的自訂類型轉換器當做自訂類別的作用中類型轉換器, 您TypeConverterAttribute必須將套用至您的類別定義。For your custom type converter to be used as the acting type converter for a custom class by .NET Framework XAML Services, you must apply the TypeConverterAttribute to your class definition. 您透過屬性指定的 ConverterTypeName 必須是您自訂類型轉換器的類型名稱。The ConverterTypeName that you specify through the attribute must be the type name of your custom type converter. 如果您套用這個屬性,則在 XAML 處理器處理屬性類型使用您自訂類別類型的值時,可以輸入字串,並傳回物件執行個體。If you apply this attribute, 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. 不是將套用get / set至類別定義, 而是將它套用至屬性定義 (主要定義, 而不是其中的執行範圍)。 TypeConverterAttributeInstead of applying a 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. 如果已套用這個屬性,則在 XAML 處理器處理該屬性的值時,可以處理輸入字串,並傳回物件執行個體。With this attribute applied, when a XAML processor handles values of that property, it can process input strings and return object instances. 如果您選擇使用 Microsoft .NET Framework 的屬性類型, 或從無法控制類別定義且無法在該處套用的TypeConverterAttribute其他程式庫, 則每個屬性類型轉換器技術特別有用。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.

若要提供自訂附加成員的類型轉換行為,請將 TypeConverterAttribute 套用至附加成員之實作模式的 Get 存取子方法。To supply a type conversion behavior for a custom attached member, apply TypeConverterAttribute to the Get accessor method of the implementation pattern for the attached member.

從標記延伸實作存取服務提供者內容Accessing Service Provider Context from a Markup Extension Implementation

任何值轉換器的可用服務都會相同。The available services are the same for any value converter. 差異在於每個值轉換器如何接收服務內容。The difference is in how each value converter receives the service context. 存取服務和可用服務記載於 Type Converters and Markup Extensions for XAML主題中。Accessing services and the services available are documented in the topic Type Converters and Markup Extensions for XAML.

XAML 節點資料流中的類型轉換器Type Converters in the XAML Node Stream

如果您是使用 XAML 節點資料流,則尚未執行類型轉換器的動作或最終結果。If you are working with a XAML node stream, the action or end result of a type converter is not yet executed. 在載入路徑中,最後需要進行類型轉換才能載入的屬性字串仍然維持為開始成員和結束成員內的文字值。In a load path, the attribute string that eventually needs to be type-converted in order to load remains as a text value within a start member and end member. 使用 XamlMember.TypeConverter 屬性可以判定這項作業最後需要的類型轉換器。The type converter that is eventually needed for this operation can be determined by using the XamlMember.TypeConverter property. 不過,從 XamlMember.TypeConverter 取得有效值是依賴具有 XAML 結構描述內容 (可透過基礎成員存取這類資訊) 或成員所使用物件值的類型。However, obtaining a valid value from XamlMember.TypeConverter relies on having a XAML schema context, which can access such information through the underlying member, or the type of the object value that the member uses. 叫用類型轉換行為時也需要 XAML 結構描述內容,因為這需要類型對應以及建立轉換器執行個體。Invoking the type conversion behavior also requires the XAML schema context because that requires type-mapping and creating a converter instance.

另請參閱See also