Forum Xamarin.Forms

Disabling Functionality Based on Behaviors

Hello, I am relatively new to Xamarin.Forms and am running into an issue I can't seem to quite figure out. I have a ScrollView with a StackLayout with several Entry fields and a save button to save a record once data entry is complete. I am trying to figure out how to disable the saving of the record (either by setting the isEnabled property to false, or stopping the save process once the button is clicked.

For instance, I have an entry field that must be an integer, so I have a behavior class setup like so:

` class IntegerValidationBehavior
public static readonly BindableProperty AttachBehaviorProperty =
propertyChanged: OnAttachBehaviorChanged);

    public static bool GetAttachBehavior(BindableObject view)
        return (bool)view.GetValue(AttachBehaviorProperty);

    public static void SetAttachBehavior(BindableObject view, bool value)
        view.SetValue(AttachBehaviorProperty, value);

    static void OnAttachBehaviorChanged(BindableObject view, object oldValue, object newValue)
        var entry = view as Entry;
        if (entry == null)

        bool attachBehavior = (bool)newValue;
        if (attachBehavior)
            entry.TextChanged += OnEntryTextChanged;
            entry.TextChanged -= OnEntryTextChanged;

    static void OnEntryTextChanged(object sender, TextChangedEventArgs args)
        int result;
        bool isValid = int.TryParse(args.NewTextValue, out result);
        ((Entry)sender).TextColor = isValid ? Color.Default : Color.Red;
        ((Entry)sender).BackgroundColor = isValid ? Color.Default : Color.Gold;

It is properly setting the text color and background color, showing that an error exists, but the user at this point would still be able to hit the save button. Here is the code I have on that button:

var saveButton = new Button { Text = "Save", }; saveButton.Clicked += async (sender, e) => { SaveReport(checkstationItem); await Navigation.PopToRootAsync(); };

My question is what is the correct way to handle this? I see behaviors mentioned all the time when talking about data validation but i'm not sure how to enforce it. I've searched the forums and couldn't find an answer to my question.



  • NickKimbroughNickKimbrough USMember ✭✭

    I suppose I should also show the code for my Entry:

    Entry length = new Entry { Placeholder = "Length", Keyboard = Keyboard.Numeric, Text = null }; length.SetBinding(Entry.TextProperty, "length"); IntegerValidationBehavior.SetAttachBehavior(length, true);

Sign In or Register to comment.