public class NumberCompareValidationBehavior : Behavior<Entry>
{
public static readonly BindableProperty TextProperty = BindableProperty.Create("Text", typeof(string),
typeof(NumberCompareValidationBehavior), null, BindingMode.TwoWay, null, propertyChanged: null);
public static readonly BindableProperty CompareTypeProperty = BindableProperty.Create("CompareType", typeof(string),
typeof(NumberCompareValidationBehavior), string.Empty);
public string Text
{
get
{
return (string)GetValue(TextProperty);
}
set
{
SetValue(TextProperty, value);
}
}
public string CompareType
{
get
{
return (string)GetValue(CompareTypeProperty);
}
set
{
SetValue(CompareTypeProperty, value);
}
}
protected override void OnAttachedTo(Entry bindable)
{
bindable.TextChanged += HandleTextChanged;
base.OnAttachedTo(bindable);
}
void HandleTextChanged(object sender, TextChangedEventArgs e)
{
if (!string.IsNullOrEmpty(e.NewTextValue))
{
bool IsValid = false;
//IsValid = e.NewTextValue == Text;
int compareValue;
bool compareIsValid = int.TryParse(Text, out compareValue);
int inputValue;
compareIsValid = int.TryParse(e.NewTextValue, out inputValue);
switch (CompareType.ToLower())
{
case "greater":
IsValid = compareIsValid && (inputValue > compareValue);
break;
case "greaterandequal":
IsValid = compareIsValid && (inputValue >= compareValue);
break;
case "lessthanandequal":
IsValid = compareIsValid && (inputValue <= compareValue);
break;
case "lessthan":
IsValid = compareIsValid && (inputValue < compareValue);
break;
default:
IsValid = true;
break;
}
((Entry)sender).TextColor = IsValid ? Color.Default : Color.Red;
((Entry)sender).Text = IsValid ? e.NewTextValue : e.OldTextValue;
}
}
protected override void OnDetachingFrom(Entry bindable)
{
bindable.TextChanged -= HandleTextChanged;
base.OnDetachingFrom(bindable);
}
}
使用:
<Entry.Behaviors>
<behaviors:EventToCommandBehavior Command="{Binding TextChangedCommand}" EventName="TextChanged" />
<customBehavior:NumberValidationBehavior/>
<customBehavior:NumberCompareValidationBehavior Text="{Binding Path= Text, Source={x:Reference controlName}}"
CompareType="lessthanandequal"/>
</Entry.Behaviors>
本文介绍了如何在Xamarin应用中使用NumberCompareValidationBehavior进行数值比较验证,详细阐述了该行为的实现和应用场景。
839

被折叠的 条评论
为什么被折叠?



