总目录
前言
本文介绍触发器:
一、属性触发器
二、数据触发器
三、事件触发器
四、多触发器
五、EnterActions和ExitActions
环境
1.Visual Studio 2017
2.Xamarin.Froms 4.0.0.8055-pre1
3.Android 4.4(API 19)或更高版本
4.约定:XF代表Xamarin.Forms
内容
触发器:控件上属性更改或事件触发时所引发的操作。有以下四种触发器:
- 属性触发器:控件属性变为特定值时触发;
- 数据触发器:被监视控件属性变为特定值时触发;
- 事件触发器:控件触发特定事件(即触发器指定的事件)时触发;
- 多触发器:另一种实现触发器的方式。
一、属性触发器
属性触发器:控件属性变为特定值时触发。
实现效果

效果描述:当Entry获取焦点时,背景色变为浅灰色。
实现方式

1.Trigger为属性触发器。
2.所有触发器主要部分如下:
- TargetType:触发器适用的控件类型;
- EnterActions和ExitActions:使用C#代码设置触发器操作;
2.Trigger主要部分如下:
- Property:要监视的控件属性。例如:本例监视属性为IsFocused;
- Value:特定值,即当监视的属性变更为此值时触发操作。例如:本例特定值设置为True,即当IsFocused值为True时触发,也就是Entry获取焦点时触发;
- Setter:设置,即触发器触发时,使用这些设置的值;
二、数据触发器
数据触发器:被监视控件属性变为特定值时触发。
实现效果


效果描述:未输入用户名时,按钮不可用;输入用户名后,按钮可用。
实现方式

1.DataTrigger为数据触发器。
2.DataTrigger通过Binding的方式设置监视控件。
注意:使用Text.Length时,需要将Entry的Text属性值设为""(即:Text=""),否则Text值为null,导致触发器失效。
三、事件触发器
事件触发器:控件触发特定事件(即触发器指定的事件)时触发。
实现效果


效果描述:点击登录按钮,按钮文本变为登录中...
实现方式

定义事件触发器触发操作类,使用此类响应事件触发器触发时的操作:
- 第一步:继承TriggerAction<T>抽象类,T为触发事件的控件,这里为Button;
- 第二步:重写Invoke方法,当事件触发器触发时调用此方法。

1.EventTrigger为事件触发器;
2.EventTrigger没有Setter。
3.EventTrigger使用Event设置监听事件,引用自定义的触发器操作类(本例为ButtonEventTriggerAction类)响应事件;
4.EventTrigger不支持五中所述的EnterActions和ExitActions。
5.可能多个Button具有相同的操作,使用触发器,可以避免重复代码。
四、多触发器
多触发器:多个触发条件满足时触发。
实现效果


效果描述:当用户名和手机号都未输入时,按钮不可用,输入任意一个时按钮可用。
实现方式

1.MultiTrigger为多触发器;
2.MultiTrigger在其Conditions中设置条件集合,只有当所有条件都满足时,才会触发Setter;
3.本例展示了输入用户名或手机号按钮便可用的效果。
下节通过值转换器实现用户名和密码必须都输入时按钮才可用的效果。
五、EnterActions和ExitActions
EnterActions和ExitActions:另一种实现触发器的方式。
实现效果


实现方式

首先定义触发器操作。

EnterActions和ExitActions:另一种实现触发器的方式。EnterActions在开始时触发,ExitActions在结束时触发,可以理解为先触发EnterActions然后再触发ExitActions,例如:本例中会先将Button的Text变为"登陆中..."在变成"登录成功"。一般这两个只定义一个即可。
后语
下篇介绍值转换器,待续...
网友评论