Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I Bind to Something Global in Xamarin Forms?

I would like to display the current user in a custom view, which most of my ContentPage's contain. I currently store the current user in the App instance as a property, after login. Attempting to just update the Label in the constructor is too early in the lifecycle.

Is there a way with Xamarin Forms to bind to this object or otherwise get the current user to update a Label in my custom view? I am using Xamarin.Forms 3.5 with the standard MVVM.

like image 319
Blanthor Avatar asked Nov 23 '25 12:11

Blanthor


1 Answers

There are a multiple approaches you could take, but the short answer is that you need something sitting between the global (static) variable and the views in order to make things work smoothly. The property on your view model must be a non-static property.

However it can have a custom implementation so that the getter retrieves the value from some global location, and in your case, you may not need a setter. The only other piece you need is to tell the view model to fire a PropertyChanged event when the user information is available, then you can use standard Binding from the Label to the view model.

Assuming you have some CurrentUser static class that has members like:

public static class CurrentUser
{
    public event Action OnLogin;   // login code needs to fire this on login
    public string Username { get; set; }
    // etc.
}

Then view models would hook up to that by doing something like:

class UserViewModel : INotifyPropertyChanged
{

    public UserViewModel()
    {
        CurrentUser.OnLogin += CurrentUser_Login;
    }

    private void CurrentUser_Login()
    {
        PropertyChanged?.Invoke(nameof(Username));
    }

    public string Username {
        get {
            return CurrentUser.Username;
        }
    }

    // etc.
}

Then the view would use <Label Text="{Binding Username}" . . .> and then when OnLogin is fired, all views would be automatically updated with the new username.

like image 173
DavidS Avatar answered Nov 25 '25 10:11

DavidS