Skip to content

Instantly share code, notes, and snippets.

@LanceMcCarthy
Created October 15, 2018 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LanceMcCarthy/a3a455848ef593eb2df1f459ef8082e9 to your computer and use it in GitHub Desktop.
Save LanceMcCarthy/a3a455848ef593eb2df1f459ef8082e9 to your computer and use it in GitHub Desktop.
Simple EmptyStringValidator Attached Property
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:SelectionPerPlatform.Portable"
xmlns:telerikInput="clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinForms.Input"
x:Class="Example.Portable.MainPage">
<telerikInput:RadEntry local:TelerikValidator.EmptyStringValidator="True"
VerticalOptions="Center"
Margin="10"/>
</ContentPage>
public static class TelerikValidator
{
public static BindableProperty EmptyStringValidatorProperty = BindableProperty.CreateAttached(
"EmptyStringValidator",
typeof(bool),
typeof(TelerikValidator),
false,
propertyChanged: EmptyStringValidatorChanged);
private static void EmptyStringValidatorChanged(BindableObject bindable, object oldValue, object newValue)
{
VisualElement radEntry = (VisualElement)bindable;
radEntry.PropertyChanged -= Entry_PropertyChanged;
if ((bool)newValue)
{
radEntry.PropertyChanged += Entry_PropertyChanged;
}
}
private static void Entry_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (sender is RadEntry entry && e.PropertyName == RadEntry.TextProperty.PropertyName)
{
entry.TextChanged += Entry_TextChanged;
}
}
private static void Entry_TextChanged(object sender, TextChangedEventArgs e)
{
if (!string.IsNullOrEmpty(e.NewTextValue))
{
(sender as RadEntry).WatermarkText = "";
(sender as RadEntry).WatermarkTextColor = Color.Gray;
}
else
{
(sender as RadEntry).WatermarkText = "text cannot be empty";
(sender as RadEntry).WatermarkTextColor = Color.Red;
}
}
public static bool GetEmptyStringValidator(BindableObject bindable)
{
return (bool)bindable.GetValue(EmptyStringValidatorProperty);
}
public static void SetEmptyStringValidator(BindableObject bindable, bool value)
{
bindable.SetValue(EmptyStringValidatorProperty, value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment