typeconverter 是 xaml 解析器的幕后英雄,自 wpf 诞生以来,它在 xaml 的运作中扮演了重要角色。尽管在 uwp 中 typeconverter 已彻底退居幕后,连自定义 typeconverter 都不可以,但了解其原理对理解 xaml 解析器的运作方式仍有帮助。
TypeConverter 在 .NET 的早期版本中就已存在,主要用于将一种类型的值转换为其他类型,典型的用法是数据类型和字符串之间的转换。
假设要实现一个从字符串转换为目标类型的函数 GetValue:
private T GetValue<T>(string source) {
var type = typeof(T);
T result;
if (type == typeof(bool)) {
result = (T)(object)Convert.ToBoolean(source);
}
else if (type == typeof(string)) {
result = (T)(object)source;
}
else if (type == typeof(short)) {
result = (T)(object)Convert.ToInt16(source);
}
else if (type == typeof(int)) {
result = (T)(object)Convert.ToInt32(source);
}
else {
result = default(T);
}
return result;
}这个函数有许多明显的问题:代码冗余、支持的类型不多、难以维护、不符合开放封闭原则等。使用
Convert.ChangeType
private T GetValue<T>(string source) {
return (T)Convert.ChangeType(source, typeof(T));
}只用一行代码,看似完美。但仔细想来,Convert 类的注释是“将一个基本数据类型转换为另一个基本数据类型”,即它只支持基础类型。实际上,ChangeType 函数的源码只是上面 GetValue 的高级版本:
public static Object ChangeType(Object value, Type conversionType, IFormatProvider provider) {
if (conversionType == null) {
throw new ArgumentNullException("conversionType");
}
Contract.EndContractBlock();
if (value == null) {
if (conversionType.IsValueType) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCastNullToValueType"));
}
return null;
}
IConvertible ic = value as IConvertible;
if (ic == null) {
if (value.GetType() == conversionType) {
return value;
}
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_IConvertible"));
}
RuntimeType rtConversionType = conversionType as RuntimeType;
if (rtConversionType == ConvertTypes[(int)TypeCode.Boolean])
return ic.ToBoolean(provider);
if (rtConversionType == ConvertTypes[(int)TypeCode.Char])
return ic.ToChar(provider);
if (rtConversionType == ConvertTypes[(int)TypeCode.SByte])
return ic.ToSByte(provider);
if (rtConversionType == ConvertTypes[(int)TypeCode.Byte])
return ic.ToByte(provider);
if (rtConversionType == ConvertTypes[(int)TypeCode.Int16])
return ic.ToInt16(provider);
if (rtConversionType == ConvertTypes[(int)TypeCode.UInt16])
return ic.ToUInt16(provider);
if (rtConversionType == ConvertTypes[(int)TypeCode.Int32])
return ic.ToInt32(provider);
if (rtConversionType == ConvertTypes[(int)TypeCode.UInt32])
return ic.ToUInt32(provider);
if (rtConversionType == ConvertTypes[(int)TypeCode.Int64])
return ic.ToInt64(provider);
if (rtConversionType == ConvertTypes[(int)TypeCode.UInt64])
return ic.ToUInt64(provider);
if (rtConversionType == ConvertTypes[(int)TypeCode.Single])
return ic.ToSingle(provider);
if (rtConversionType == ConvertTypes[(int)TypeCode.Double])
return ic.ToDouble(provider);
if (rtConversionType == ConvertTypes[(int)TypeCode.Decimal])
return ic.ToDecimal(provider);
if (rtConversionType == ConvertTypes[(int)TypeCode.DateTime])
return ic.ToDateTime(provider);
if (rtConversionType == ConvertTypes[(int)TypeCode.String])
return ic.ToString(provider);
if (rtConversionType == ConvertTypes[(int)TypeCode.Object])
return (Object)value;
return ic.ToType(conversionType, provider);
}TypeConverter 的一个典型应用场景就是解决这个问题。使用 TypeConverter 重构这个函数如下:
private T GetValue<T>(string source) {
var typeConverter = TypeDescriptor.GetConverter(typeof(T));
if (typeConverter.CanConvertTo(typeof(T)))
return (T)typeConverter.ConvertFromString(source);
return default(T);
}TypeConverter GetConverter(Type type)
值得一提的是,如果使用了错误的字符串,Convert.ChangeType 只提示“输入字符串的格式不正确”。而 TypeConverter 的错误提示则详细得多:"a 不是 Decimal 的有效值"。
XAML 本质上是 XML,其中的属性内容全部都是字符串。如果对应属性的类型是 XAML 内置类型(即 Boolean, Char, String, Decimal, Single, Double, Int16, Int32, Int64, TimeSpan, Uri, Byte, Array 等类型),XAML 解析器直接将字符串转换成对应值赋给属性;对于其他类型,XAML 解析器需做更多工作。
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>如上面这段 XAML 中的 "Auto" 和 "*",XAML 解析器将其分别解析成 GridLength.Auto 和 new GridLength(1, GridUnitType.Star) 再赋值给 Height,它相当于这段代码:
grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });为了完成这项工作,XAML 解析器需要 TypeConverter 的协助。XAML 解析器通过两个步骤查找 TypeConverter:1. 检查属性声明上的 TypeConverterAttribute。2. 如果属性声明中没有 TypeConverterAttribute,检查类型声明中的 TypeConverterAttribute。
属性声明上 TypeConverterAttribute 的优先级高于类型声明。如果以上两步都找不到类型对应的 TypeConverterAttribute,XAML 解析器将会报错:属性 "*" 的值无效。找到 TypeConverterAttribute 指定的 TypeConverter 后,XAML 解析器调用它的
object ConvertFromString(string text)
WPF 内置的 TypeConverter 非常多,但有时还是需要自定义 TypeConverter,一种情况是难以用字符串直接构建的类型,一种是为了简化 XAML。
假设有三个类 Email、Receiver、ReceiverCollection,结构如下:
public class Email {
public ReceiverCollection Receivers { get; set; }
}
<p>public class Receiver {
public string Name { get; set; }
}</p><p>public class ReceiverCollection : ObservableCollection<Receiver> {}在 XAML 中构建一个 Email 对象及填充 Receiver 列表的代码如下:
<Email x:Key="Email"> <Email.Receivers> <ReceiverCollection> <Receiver Name="Zhao"></Receiver> <Receiver Name="Qian"></Receiver> <Receiver Name="Sun"></Receiver> <Receiver Name="Li"></Receiver> <Receiver Name="Zhou"></Receiver> <Receiver Name="Wu"></Receiver> </ReceiverCollection> </Email.Receivers> </Email>
语法如此复杂,这时就需要考虑自定义一个 ReceiverCollectionConverter。自定义 TypeConverter 的基本步骤如下:
创建一个继承自 TypeConverter 的类;重载
virtual bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType);
virtual bool CanConvertTo(ITypeDescriptorContext context, Type destinationType);
virtual object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value);
virtual object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType);
[TypeConverter(typeof(ReceiverCollectionConverter))]
public class ReceiverCollection : ObservableCollection<Receiver> {
public static ReceiverCollection Parse(string source) {
var result = new ReceiverCollection();
var tokens = source.Split(';');
foreach (var token in tokens) {
result.Add(new Receiver { Name = token });
}
return result;
}</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">public string ConvertToString() {
var result = string.Empty;
foreach (var item in this) {
result += item.Name;
result += ";";
}
return result;
}}
public class ReceiverCollectionConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); }
<pre class="brush:php;toolbar:false;">public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
if (destinationType == typeof(string)) {
return true;
}
return base.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
switch (value) {
case null:
throw GetConvertFromException(null);
case string source:
return ReceiverCollection.Parse(source);
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
switch (value) {
case ReceiverCollection instance:
if (destinationType == typeof(string)) {
return instance.ConvertToString();
}
break;
}
return base.ConvertTo(context, culture, value, destinationType);
}}
结果上面那段 XAML 可以简化成一句代码:
<Email Receivers="Zhao;Qian;Sun;Li;Zhou;Wu" x:Key="Email"></Email>
除了可以在类型上声明 TypeConverterAttribute,还可以在属性上声明,属性上的声明优先级较高:
public class Email {
[TypeConverter(typeof(ReceiverCollectionConverterExtend))]
public ReceiverCollection Receivers { get; set; }
}在 UWP 中,TypeConverter 已彻底退居幕后。要实现上面 ReceiverCollectionConverter 的简化 XAML 效果,可以使用 CreateFromStringAttribute(自 Aniverssary Update(14393) 后可用,但常常报错,直接升到 Creators Update(15063) 较好):
[Windows.Foundation.Metadata.CreateFromString(MethodName = "TypeConverterUwp.ReceiverCollection.Parse")]
public class ReceiverCollection : ObservableCollection<Receiver> {
public static ReceiverCollection Parse(string source) {
var result = new ReceiverCollection();
var tokens = source.Split(';');
foreach (var token in tokens) {
result.Add(new Receiver { Name = token });
}
return result;
}
}CreateFromStringAttribute 的效果和 TypeConverterAttribute 差不多,但它只能用在类上,不能用于属性。即使提供了这个补偿方案,不能自定义 TypeConverter 对 UWP 的影响还是很大。UWP 有 XAML 固有数据类型的概念(即可以直接在 XAML 上使用的数据类型),只包含 Boolean、String、Double、Int32 四种,而内置的 TypeConverter 又非常少,导致连 decimal 都没有获得支持。
有趣的是,Visual Studio 的属性面板还天真地以为自己支持直接输入 Decimal,甚至设计视图还可以正常显示,但编译报错。通过引用 System.ComponentModel.TypeConverter 的 NuGet 包连 TypeConverterAttribute 都可以添加,但这个 Attribute 没有任何实际效果。
public class MyContentControl : ContentControl {
/// <summary>
/// 获取或设置 Amount 的值
/// </summary>
[TypeConverter(typeof(DecimalConverter))]
public Decimal Amount {
get { return (Decimal)GetValue(AmountProperty); }
set { SetValue(AmountProperty, value); }
}</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">/// <summary>
/// 标识 Amount 依赖属性。
/// </summary>
public static readonly DependencyProperty AmountProperty =
DependencyProperty.Register("Amount", typeof(Decimal), typeof(MyContentControl), new PropertyMetadata(0m, OnAmountChanged));
private static void OnAmountChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) {
MyContentControl target = obj as MyContentControl;
Decimal oldValue = (Decimal)args.OldValue;
Decimal newValue = (Decimal)args.NewValue;
if (oldValue != newValue)
target.OnAmountChanged(oldValue, newValue);
}
protected virtual void OnAmountChanged(Decimal oldValue, Decimal newValue) {
Content = "Amount is " + newValue;
}}
当看到如上图那样的错误信息,可以理解为 UWP 缺少对应类型的 TypeConverter,只能在 CodeBehind 为属性赋值。如果一定要在 XAML 上为 decimal 赋值,可以使用 Binding。
public class StringToDecimalBridge {
public Decimal this[string key] {
get {
return Convert.ToDecimal(key);
}
}
}<MyContentControl Amount="{Binding [10.3],Source={StaticResource StringToDecimalBridge}}"></MyContentControl>因为本地化的文章提到 TypeConverter,正好手头的工作要用到 TypeConverter,所以才想写一篇文章介绍这个概念。结果才发现 UWP 的 TypeConverter 不能直接使用,偏偏这个概念对理解 XAML 解析器很重要,正好把 WPF 的内容也拿来讨论一下。
TypeConverter 类 TypeConverters 和 XAML Type Converters for XAML Overview TypeConverterAttribute Class 如何:实现类型转换器 XAML 固有数据类型 CreateFromStringAttribute Class
GitHub - TypeConverterSample
以上就是[UWP]了解TypeConverter的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号