Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 77050

Behavior in Entry crashs app if the Entry is empty

$
0
0

I have this behavior over an Entry control:

public class EntryLengthValidatorBehavior : Behavior<Entry>
{
    public int MaxLength { get; set; }

    protected override void OnAttachedTo(Entry bindable)
    {
        base.OnAttachedTo(bindable);
        bindable.TextChanged += OnEntryTextChanged;
    }

    protected override void OnDetachingFrom(Entry bindable)
    {
        base.OnDetachingFrom(bindable);
        bindable.TextChanged -= OnEntryTextChanged;
    }

    void OnEntryTextChanged(object sender, TextChangedEventArgs e)
    {
        var entry = (Entry)sender;

        //Se o texto informado foi maior que o tamanho definido
        if (entry.Text.Length > this.MaxLength)
        {
            string entryText = entry.Text;

            entryText = entryText.Remove(entryText.Length - 1); //remove o ultimo numero

            entry.Text = entryText;
        }
    }
}

And I implement it as below:

            <StackLayout Orientation="Horizontal" HorizontalOptions="Start" VerticalOptions="Center" WidthRequest="250">
                <Image Source="ic_credit_card_grey_600_36dp.png" Aspect="AspectFill" Margin="2"></Image>
                <Entry x:Name="Numero" Text="{Binding Cartao.Numero, Converter={StaticResource cvtMaskedCard}}" Placeholder="Número do Cartão" HorizontalOptions="FillAndExpand" IsEnabled="{Binding CartaoEnabled}" Keyboard="Numeric">
                    <Entry.Behaviors>
                        <mybehaviors:EntryLengthValidatorBehavior MaxLength="16" />
                    </Entry.Behaviors>
                </Entry>

My intention is limit the maxlength to 16 caracteres.

This entry is part of a login pageview. If I do not type anything, and submit the page, I get this error:

System.Exception:

If I remove this behavior, everything works fine... I need to limit the length but there is the possibility the user do not type anything and if it happens, the app crashes.

How to resolve it ?

Thanks.


Viewing all articles
Browse latest Browse all 77050

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>