在Xamarin.Forms工程中使用XAML创建自定义控件。
参考:Creating Reusable XAML User Controls with Xamarin Forms
源代码:XamarinCustomControl
作用
- 拆分复杂页面;
- 复用组件。
创建控件
- 新建一个普通页面,包含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中对应的布局,可以用类的成员将控件子元素的属性或子元素本身暴露到外部:
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; } } //响应子元素的事件 public void OnLoginClicked(object sender, EventArgs e) { } }
引用控件
- 在外部页面的XAML中,为ContentPage标签添加属性:
xmlns:custom_controls="clr-namespace:CustomControlTest;assembly=CustomControlTest.App"
- 在外部页面的XAML中引用控件并设置绑定的变量:
<custom_controls:MyCustomControl x:Name="qqLogin" BindingContext="{Binding QQ}"/>
- 在外部页面的.cs文件中定义绑定到控件的变量和访问控件属性:
//定义绑定到控件的变量 this.QQ = new MyControlSpec { Icon = "qq_logo", Title = "QQ" }; BindingContext = this; //设置控件的属性 this.qqLogin.TextColor = Color.Blue; //通过控件属性获取子元素 Label wxLabel = this.wxLogin.TextControl; wxLabel.FontSize = 20;