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.
public class LoginButtonBehavior : Behavior
{
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.
You can read more about behaviors at Xamarin's developer portal, https://developer.xamarin.com/guides/xamarin-forms/working-with/behaviors/
3/14/2016 - 1:15 PM