# XamarinCustomControl
**Repository Path**: DearXx/XamarinCustomControl
## Basic Information
- **Project Name**: XamarinCustomControl
- **Description**: Xamarin.Forms自定义XAML控件
- **Primary Language**: C#
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 1
- **Created**: 2018-04-21
- **Last Updated**: 2020-12-18
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
在Xamarin.Forms工程中,使用XAML创建自定义控件。参考:[Creating Reusable XAML User Controls with Xamarin Forms](https://blog.falafel.com/creating-reusable-xaml-user-controls-xamarin-forms/)
## 作用
1. 拆分复杂页面;
1. 复用组件。
## 创建控件
1. 新建一个普通页面,包含XAML文件和cs文件;
1. 将XAML中的ContentPage改为任意布局,并在其中放置控件的子元素,可以使用Binding将子元素的属性绑定到外部变量:
```
```
1. 将.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) {
}
}
```
## 引用控件
1. 在外部页面的XAML中,为ContentPage标签添加属性:
```
xmlns:custom_controls="clr-namespace:CustomControlTest;assembly=CustomControlTest.App"
```
1. 在外部页面的XAML中引用控件并设置绑定的变量:
```
```
1. 在外部页面的.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;
```