在Xamarin.Forms工程中使用XAML創(chuàng)建自定義控件。
參考:Creating Reusable XAML User Controls with Xamarin Forms
源代碼:XamarinCustomControl
作用
- 拆分復(fù)雜頁面;
- 復(fù)用組件。
創(chuàng)建控件
- 新建一個普通頁面,包含XAML文件和cs文件;
- 將XAML中的ContentPage改為任意布局,并在其中放置控件的子元素,可以使用Binding將子元素的屬性綁定到外部變量:
<?xml version="1.0" encoding="UTF-8"?> <StackLayout xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="CustomControlTest.MyCustomControl"> <Image x:Name="Icon" Source="{Binding Icon}" /> <Label x:Name="Text" Text="{Binding Title}" HorizontalOptions="Center" LineBreakMode="NoWrap" Font="Small" /> <Button x:Name="Login" Text="Login" Clicked="OnLoginClicked"/> </StackLayout> - 將.cs文件中的基類由ContentPage改為XAML中對應(yīng)的布局,可以用類的成員將控件子元素的屬性或子元素本身暴露到外部:
public partial class MyCustomControl : StackLayout { //暴露子元素的屬性 public Color TextColor { get { return this.Text.TextColor; } set { this.Text.TextColor = value; } } //暴露子元素 public Label TextControl { get { return this.Text; } set { this.Text = value; } } //響應(yīng)子元素的事件 public void OnLoginClicked(object sender, EventArgs e) { } }
引用控件
- 在外部頁面的XAML中,為ContentPage標(biāo)簽添加屬性:
xmlns:custom_controls="clr-namespace:CustomControlTest;assembly=CustomControlTest.App" - 在外部頁面的XAML中引用控件并設(shè)置綁定的變量:
<custom_controls:MyCustomControl x:Name="qqLogin" BindingContext="{Binding QQ}"/> - 在外部頁面的.cs文件中定義綁定到控件的變量和訪問控件屬性:
//定義綁定到控件的變量 this.QQ = new MyControlSpec { Icon = "qq_logo", Title = "QQ" }; BindingContext = this; //設(shè)置控件的屬性 this.qqLogin.TextColor = Color.Blue; //通過控件屬性獲取子元素 Label wxLabel = this.wxLogin.TextControl; wxLabel.FontSize = 20;