[Xamarin][筆記]簡介Attached Property

  • 797
  • 0

Attached property 是一種特殊型別的Bindable property,它可以掛載在XAML中某一個物件上,讓該物件擁有這個屬性,而不需要定義屬性在該物件內。例如在Grid中的Child物件,可以使用Grid.RowGrid.Column這兩個attached properties以定義在Grid中的位置。而Grid.RowGrid.Column其實並不是定義在Grid的Child物件中。 Attached property也被應用在Attached Behaviors上,透過Behavior以簡便的擴充Control的功能。

 

建立Attached Property

基本上,attached property是Bindable property,所以它的建立方法也很類似。

  1. 使用BindableProperty.CreateAttached()建立BindableProperty型別的屬性
  2. 提供GetPropertyName() 與 SetPropertyName() 以存取attached property

Creating a Property

跟Bindable property類似,不過是使用CreateAttached()來建立屬性。也需要遵守相同的Naming Convention-命名必須是指定的屬性名稱(例如Sample Code中的HasShadow),加上Property結尾。

public static readonly BindableProperty HasShadowProperty =
  BindableProperty.CreateAttached ("HasShadow", typeof(bool), typeof(ShadowEffect), false);

Creating Accessors

需要建立兩個static的method,GetPropertyNameSetPropertyName以作為attached property 的Accessor,否則Xamarin.Form property system無法正確地存取此attached property。

public static bool GetHasShadow (BindableObject view)
{
  return (bool)view.GetValue (HasShadowProperty);
}

public static void SetHasShadow (BindableObject view, bool value)
{
  view.SetValue (HasShadowProperty, value);
}

使用Attached Property

當attached property建立好之後,就可以使用XAML或是C# Code以使用它。如果使用XAML,需要先宣告namespace

<ContentPage ... xmlns:local="clr-namespace:EffectsDemo" ...>
  ...
</ContentPage>

當namespace宣告好了之後,就可以將此attached property使用在我們的目標control上。

<Label Text="Label Shadow Effect" local:ShadowEffect.HasShadow="true" />

如果是C#,其使用方式如下:

var label = new Label { Text = "Label Shadow Effect" };
ShadowEffect.SetHasShadow (label, true);

使用Style設定Attached Property

如同以下的Code,可以設定attached property在Style中,以進行共用。

<Style x:Key="ShadowEffectStyle" TargetType="Label">
  <Style.Setters>
    <Setter Property="local:ShadowEffect.HasShadow" Value="true" />
  </Style.Setters>
</Style>

上面的Style是explicit style,所以取得key 值就可以套用在Control上

<Label Text="Label Shadow Effect" Style="{StaticResource ShadowEffectStyle}" />