微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决创建一个自定义 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 方法中 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);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?