问题描述
我正在尝试为自定义视图创建自定义 BindableProperty
,该视图在通过 XAML 使用时接收字符串,但在内部实现为自定义结构,如下所示:
struct X {
public Y A;
public Z B;
// Y and Z are data types
// pertaining to a struct
}
public class MyView : CustomView {
public static readonly BindableProperty
MyValueProperty = BindableProperty.Create
(propertyName: "MyValue",returnType: typeof(string),declaringType: typeof(MyView),defaultValue: null,defaultBindingMode: BindingMode.TwoWay,propertyChanged: MyValuePropertyChanged);
static void MyValuePropertyChanged(BindableObject obj,object oldValue,object newValue) {
MyView view = (MyView)obj;
string enteredStringValue = (string)newValue;
// Set the MyValue field as required
}
public X MyValue {
// Implement getters and setters
}
}
我最初创建上述属性的本能是声明上述字段,并根据 X
方法中 XAML 中传递的 string
生成所需的 struct MyValuePropertyChanged
实例,但被认为是不可能的,因为在运行时抛出异常表明这种声明是非法的。
在概要中,我试图复制 Xamarin.Forms.GridLength
结构的行为,当通过 getter 和 setter 访问时,该结构的 XAML 代码中的字符串表示将转换为所需的结构。
提前致谢。
解决方法
上述行为可以通过继承 Xamarin.Forms.TypeConverter
类定义自定义类型转换器并通过 Xamarin.Forms.Xaml.TypeConversion
属性装饰上述自定义转换器并通过 Xamarin.Forms.TypeConverter
装饰相关结构来实现属性如下:
public static readonly BindableProperty
MyValueProperty = BindableProperty.Create
(propertyName: nameof(MyValue),returnType: typeof(X),declaringType: typeof(MyView),defaultValue: null,defaultBindingMode: BindingMode.TwoWay,propertyChanged: MyValuePropertyChanged);
[TypeConverter(typeof(XConverter))]
struct X; // Declaration omitted in answer
[TypeConversion(typeof(X))]
class XConverter : TypeConverter {
public override object
ConvertFromInvariantString(string value) {
if (value == null) return null;
// Return the object corresponding to the passed
// string representation of the said object
}
}
也可以在需要时使用 Xamarin 预定义的转换器,如下所示:
public static readonly BindableProperty
SizeProperty = BindableProperty.Create
(propertyName: nameof(Size),returnType: typeof(double),declaringType: typeof(TestClass));
[TypeConverter(typeof(Xamarin.Forms.FontSizeConverter))]
public double Size {
get => (double)GetValue(SizeProperty);
set => SetValue(SizeProperty,value);
}