From a6f0daf0a8d77740a2065dd46e91a58d2e22c38c Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Fri, 7 Oct 2016 14:26:43 +0200 Subject: [PATCH] A max length --- .../BookAStar/Behaviors/MaxLengthValidator.cs | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 BookAStar/BookAStar/Behaviors/MaxLengthValidator.cs diff --git a/BookAStar/BookAStar/Behaviors/MaxLengthValidator.cs b/BookAStar/BookAStar/Behaviors/MaxLengthValidator.cs new file mode 100644 index 00000000..e35a5d14 --- /dev/null +++ b/BookAStar/BookAStar/Behaviors/MaxLengthValidator.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Xamarin.Forms; + +namespace BookAStar.Behaviors +{ + public class MaxLengthValidator : Behavior + { + public static readonly BindableProperty MaxLengthProperty = BindableProperty.Create("MaxLength", typeof(int), typeof(MaxLengthValidator), 0); + + public int MaxLength + { + get { return (int)GetValue(MaxLengthProperty); } + set { SetValue(MaxLengthProperty, value); } + } + + protected override void OnAttachedTo(Entry bindable) + { + bindable.TextChanged += bindable_TextChanged; + } + + private void bindable_TextChanged(object sender, TextChangedEventArgs e) + { + //if (MaxLength != null && MaxLength.HasValue) + if (e.NewTextValue.Length > 0 && e.NewTextValue.Length > MaxLength) + ((Entry)sender).Text = e.NewTextValue.Substring(0, MaxLength); + } + + protected override void OnDetachingFrom(Entry bindable) + { + bindable.TextChanged -= bindable_TextChanged; + + } + } +}