[Xamarin][筆記]簡介Bindable Properties

  • 1447
  • 0

Bindable Properties是一種特別型態的property,它的值會被Xamarin.Forms property system所追蹤。所以可以支援data binding, styles, templates,及通知value的改變。

每一個Bindable Property都會有一個相對的BindableProperty 型別的 public static readonly property。Label.Text就是一種Bindable Properties,所以相對會有Label.TextProperty

 

建立Bindable Property

要建立Bindable Property的步驟如下:

1.使用BindableProperty.Create 建立 BindableProperty物件

在自訂的Control底下,使用BindableProperty.Create() method建立BindableProperty 型別的 public static readonly property。這裡是有Naming convention的,就是名稱必須是指定的屬性名稱(例如Sample Code中的MyProp),加上Property結尾

public class MyEntry : Entry
{
	public static readonly BindableProperty MyPropProperty =
  		BindableProperty.Create (
			"MyProp", //屬性名稱
			typeof(string), //屬性型別
			typeof(MyEntry), //擁有此屬性的型別	
			"None", //預設值
			propertyChanged: OnMyPropChanged
	);

	static void OnMyPropChanged (BindableObject bindable, object oldValue, object newValue)
	{
  		//屬性值變更時,要進行的處理
	}
}

2.建立Accessor

Accessor是要用來使用property的語法來存取bindable property

以下是對應上面Sample的Accessor,名稱是BindableProperty.Create() method所指定的MyProp,型別是BindableProperty.Create()指定的string

public string MyProp {
  get { return (string)GetValue(EventNameProperty); }
  set { SetValue(EventNameProperty, value); }
}

使用Bindable Property

如以下的XAML,使用我們自訂的Control時,就可以使用該property。

<MyEntry MyProp="Email" />

參考