Xamarin 表单触发器示例
Trigger
s 是一种为应用程序添加一些 UX 响应的简单方法。一个简单的方法是添加一个 Trigger
,根据其相关的 Entry
是否输入了文本来更改 Label
的 TextColor
。
使用 Trigger
可以使 Label.TextColor
从灰色(没有输入文本时)变为黑色(一旦用户输入文本):
转换器(每个转换器都有一个 Instance
变量,用于绑定,因此每次使用时都不会创建类的新实例):
/// <summary>
/// Used in a XAML trigger to return <c>true</c> or <c>false</c> based on the length of <c>value</c>.
/// </summary>
public class LengthTriggerConverter : Xamarin.Forms.IValueConverter {
/// <summary>
/// Used so that a new instance is not created every time this converter is used in the XAML code.
/// </summary>
public static LengthTriggerConverter Instance = new LengthTriggerConverter();
/// <summary>
/// If a `ConverterParameter` is passed in, a check to see if <c>value</c> is greater than <c>parameter</c> is made. Otherwise, a check to see if <c>value</c> is over 0 is made.
/// </summary>
/// <param name="value">The length of the text from an Entry/Label/etc.</param>
/// <param name="targetType">The Type of object/control that the text/value is coming from.</param>
/// <param name="parameter">Optional, specify what length to test against (example: for 3 Letter Name, we would choose 2, since the 3 Letter Name Entry needs to be over 2 characters), if not specified, defaults to 0.</param>
/// <param name="culture">The current culture set in the device.</param>
/// <returns><c>object</c>, which is a <c>bool</c> (<c>true</c> if <c>value</c> is greater than 0 (or is greater than the parameter), <c>false</c> if not).</returns>
public object Convert(object value, System.Type targetType, object parameter, CultureInfo culture) { return DoWork(value, parameter); }
public object ConvertBack(object value, System.Type targetType, object parameter, CultureInfo culture) { return DoWork(value, parameter); }
private static object DoWork(object value, object parameter) {
int parameterInt = 0;
if(parameter != null) { //If param was specified, convert and use it, otherwise, 0 is used
string parameterString = (string)parameter;
if(!string.IsNullOrEmpty(parameterString)) { int.TryParse(parameterString, out parameterInt); }
}
return (int)value > parameterInt;
}
}
XAML(XAML 代码使用 Entry
的 x:Name
来计算 Entry.Text
属性超过 3 个字符。):
<StackLayout>
<Label Text="3 Letter Name">
<Label.Triggers>
<DataTrigger TargetType="Label"
Binding="{Binding Source={x:Reference NameEntry},
Path=Text.Length,
Converter={x:Static helpers:LengthTriggerConverter.Instance},
ConverterParameter=2}"
Value="False">
<Setter Property="TextColor"
Value="Gray"/>
</DataTrigger>
</Label.Triggers>
</Label>
<Entry x:Name="NameEntry"
Text="{Binding MealAmount}"
HorizontalOptions="StartAndExpand"/>
</StackLayout>