Let’s define a simple Entry centered on the ContentPage. It gets the behavior LimitedLength, which will check the length of the entered text and adjusts the text color accordingly. But at the moment, we don’t have to know the details. We simply define it to behave like an entry with limited length.
MainPage = new ContentPage {
Content = new Entry {
VerticalOptions = LayoutOptions.CenterAndExpand,
Behaviors = { new LimitedLength() },
},
};
The LimitedLength behavior is implemented as follows. When attached to or detached from a view, it subscribes or unsubscribes an event handler HandleTextChanged. The handler itself sets the TextColor of the sender to Default or Red depending on the Text.Length.
public class LimitedLength : Behavior<Entry>
{
protected override void OnAttachedTo(Entry bindable)
{
bindable.TextChanged += HandleTextChanged;
}
protected override void OnDetachingFrom(Entry bindable)
{
bindable.TextChanged -= HandleTextChanged;
}
static void HandleTextChanged(object sender, TextChangedEventArgs e)
{
var entry = sender as Entry;
entry.TextColor = entry.Text.Length < 10 ? Color.Default : Color.Red;
}
}
So when entering a long string, the text color remains black until the tenth character is entered. Then the input is highlighted with red color to indicate an invalid entry.