首页 > 解决方案 > 创建一个自定义 BindableProperty,它采用 XAML 中基础返回类型的自定义定义字符串表示形式

问题描述

我正在尝试为自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针对方法中string传入的 XAML生成所需的结构实例MyValuePropertyChanged,但这被认为是不可能的,因为在运行时抛出异常表示此类声明的非法性.

在概要中,我试图复制Xamarin.Forms.GridLength结构的行为,其在 XAML 代码中的字符串表示在通过 getter 和 setter 访问时被转换为所需的结构。

提前致谢。

标签: c#xamarinxamarin.formsbindableproperty

解决方案


上述行为可以通过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);
}

推荐阅读