Search code examples
xamarinrealm

Use realm and MVVMLight


I use MVVMLight to develop and app in Xamarin. My team uses iOS and Android native, so not Xamarin Forms.

We use Realm to store data in, and want to use MVVMLight to bind data to the UI. We have a public IRealmCollection<Info> InfoList { get; private set; }.

The ObservableCollection<T> have a GetController to bind the data. (https://mallibone.com/post/mvvm-light-ios-uitableview-binding)

Does Realm for Xamarin have something similar so we can bind data to the UI?


Solution

  • Unfortunately the MVVMLight codebase has a hard requirement on the observable collection being IList<T> which is more restricting than the API provided by Realm. The good news is that it's open source, so you can easily make the modifications needed to make it work. You'll need ObservableTableViewController and ObservableTableViewSource. Then just modify all DataSource properties/fields to be IReadOnlyList<T> instead of IList<T>. Then the GetController extension method can be modified to be:

    public static ObservableTableViewController<TItem> GetController<TItem>(
        this IReadOnlyList<TItem> collection,
        Func<NSString, UITableViewCell> createCellDelegate,
        Action<UITableViewCell, TItem, NSIndexPath> bindCellDelegate,
        string reuseId = null)
    {
        return new ObservableTableViewController<TItem>
        {
            DataSource = collection,
            CreateCellDelegate = createCellDelegate,
            BindCellDelegate = bindCellDelegate,
            ReuseId = reuseId,
        };
    }