diff --git a/BookAStar/BookAStar/Behaviors/DecimalValidatorBehavior.cs b/BookAStar/BookAStar/Behaviors/DecimalValidatorBehavior.cs new file mode 100644 index 00000000..c9b48923 --- /dev/null +++ b/BookAStar/BookAStar/Behaviors/DecimalValidatorBehavior.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Xamarin.Forms; + +namespace BookAStar.Behaviors +{ + public class DecimalValidatorBehavior : Behavior + { + // Creating BindableProperties with Limited write access: http://iosapi.xamarin.com/index.aspx?link=M%3AXamarin.Forms.BindableObject.SetValue(Xamarin.Forms.BindablePropertyKey%2CSystem.Object) + + static readonly BindablePropertyKey IsValidPropertyKey = BindableProperty.CreateReadOnly("IsValid", typeof(bool), typeof(DecimalValidatorBehavior), false); + + public static readonly BindableProperty IsValidProperty = IsValidPropertyKey.BindableProperty; + + public bool IsValid + { + get { return (bool)base.GetValue(IsValidProperty); } + private set { base.SetValue(IsValidPropertyKey, value); } + } + + protected override void OnAttachedTo(Entry bindable) + { + bindable.TextChanged += bindable_TextChanged; + } + + private void bindable_TextChanged(object sender, TextChangedEventArgs e) + { + decimal result; + IsValid = decimal.TryParse(e.NewTextValue, out result); + ((Entry)sender).TextColor = IsValid ? Color.Default : Color.Red; + + } + + protected override void OnDetachingFrom(Entry bindable) + { + bindable.TextChanged -= bindable_TextChanged; + } + } +}