Use behaviors to handle states in Xamarin.Forms

I often see code that for example binds colors and texts for a button when they want to show different color and/or text when app is in different states. For example a button for login/logout the XAML could look like below.

<Button Color="{Binding ButtonColor}" Text="{Binding ButtonText} />

It will work but I don’t want to define the UI in view models.

My solution is to create behaviors for the controls. The behaviors should be so general as possible to increase the reusability. In this case it will be a LoginButtonBehavior.

public class LoginButtonBehavior : Behavior<CircleImage>
    {
        public static readonly BindableProperty IsLoggedInProperty =
        BindableProperty.Create("IsLoggedIn", typeof(bool), typeof(LoginButtonBehavior),
            null, propertyChanged: (bindable, oldValue, newValue) => {
                var behavior = (LoginButtonBehavior)bindable;
                behavior.Update();
            });
 
        public bool IsLoggedIn
        {
            get
            {
                return (bool)GetValue(IsLoggedInProperty);
            }
            set
            {
                SetValue(IsLoggedInProperty, value);
            }
        }
 
 
        public Button Control { get; set; }
 
        protected override void OnAttachedTo(Button bindable)
        {
            base.OnAttachedTo(bindable);
 
            Control = bindable;
 
           bindable.BindingContextChanged += (sender, _) => this.BindingContext = ((BindableObject)sender).BindingContext;
        }
 
        public void Update()
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                 if(IsLoggedIn)
                 {
                       Control.BackgroundColor = Color.Red;
                       Control.Text = "Logout";
                 }
                 else
                 {
                       Control.BackgroundColor = Color.Green;
                       Control.Text = "Login";
                 }
            });
        }
    }

When we have created the behavior we will attach it to the button.

<Button>
     <Button.Behaviors>
          <behaviors:LoginButtonBehavior IsLoggedIn="{Binding IsLoggedIn}" />
     </Button.Behaviors>
</Button>

You can read more about behaviors at Xamarin’s developer portal, https://developer.xamarin.com/guides/xamarin-forms/working-with/behaviors/

4 thoughts on “Use behaviors to handle states in Xamarin.Forms

  1. stfnilsson says:

    Hmm. For me Mvvm is about abstracting state and behavior from view to viewmodel… I try to use the viewmodels as much as possible..views should be dumb as *

    But StateTriggers(uwp) and Behavior have its purpose..

    I even try to localize from viewmodels..

Leave a Reply

Your email address will not be published. Required fields are marked *