Xamarin.Tip – Bindable iOS UIRefreshControl

Here’s another super simple tip that has made my life easier with a basic control for iOS – the BindableRefreshControl. The premise is to wrap the BeginRefreshing() and EndRefreshing() calls into a bindable property that can be applied with a one-way binding from a ViewModel.

To premise this a bit, the existing UIRefreshControl from iOS has the two methods mentioned above as well as a Refreshing bool property that is readonly. The need for wrapping this in a property came from wanting to bind my native ViewControllers to a ViewModel and a property such as IsLoading.

So here’s the control:

BindableRefreshControl.cs

    /// <summary>
    /// Bindable refresh control.
    /// Adds a refresh event to bind to.
    /// </summary>
    public class BindableRefreshControl : UIRefreshControl
    {
        private bool _isRefreshing;
        public bool IsRefreshing
        {
            get
            {
                return _isRefreshing;
            }
            set
            {
                _isRefreshing = value;
                if (value)
                    BeginRefreshing();
                else
                    EndRefreshing();
            }
        }
    }

Yeah that’s literally it.

However, I now can use it like this (using MvvmLight):

MainViewModel.cs

public class MainViewModel : ViewModelBase
{
    private bool _isLoading;
    public bool IsLoading
    {
        get
        {
            return _isLoading;
        }
        set
        {
            Set(ref _isLoading, value);
        }
    }
}

And in the ViewController:
MainViewController.cs

public class MainViewController : UIViewController
{
    private BindableRefreshControl _refreshControl;
    private MainViewModel _viewModel;
    protected override void ViewDidLoad() 
    {
        _viewModel = new MainViewModel();
        _refreshControl = new BindableRefreshControl();
        ...
        ...
        this.SetBinding(() => _viewModel.IsLoading,
                        () => _refreshControl.IsRefreshing));
    }
}

And like that, your native iOS spinners can be easily bound to your view model properties!


If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Advertisements

One thought on “Xamarin.Tip – Bindable iOS UIRefreshControl”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s