Krzysztof Kaźmierczak
Krzysztof Kaźmierczak

Reputation: 1434

Problem with binding to MvxView with Xamarin.iOS and MvvmCross

I have a problem with implementing following scenario using Xamarin.iOS and MvvmCross (6.2.3.0). I have a view and in it's viewmodel I have a property which is a list of objects. I need to dynamically generate a label and a textfield for each of this list entry on my view. So I decided to implement a custom view for this. Here is what I tried so far:

In my viewcontroller, in CreateView I simply add my custom UIView. I can see it's content on my view. In ViewDidLoad() I create bindings:

private void CreateBindings()
{
var set = this.CreateBindingSet<MyController, MyViewModel>();
set.Bind(myCustomControl).For(x => x.DataContext).To(vm => vm.MyListOfObjects);
set.Apply();
}

MyCustomControl code is as follows:

public class MyCustomControl : MvxView
{
public MyCustomControl() {

//DataContext is always null here!
//I'd like to get access to list of objects here, add controls for each entry and make sure they are binded to a viewmodel's list of objects somehow.
}

}

I noticed that the list of objects in my viewmodel is set later than a constructor call for MyCustomControl is being made, so it makes sense that DataContext in MyCustom control is null. I'm missing something obvious I believe. Can someone point me in a proper direction? I would be very grateful.

I tried this example, which is exactly what I'm trying to achieve, but no luck so far ;(

N=32 - ViewModels and MvxView on the iPad - N+1 days of MvvmCross https://www.youtube.com/watch?v=cYu_9rcAJU4&list=PLR6WI6W1JdeYSXLbm58jwAKYT7RQR31-W&index=35&t=1649s

Upvotes: 0

Views: 371

Answers (1)

kmiterror
kmiterror

Reputation: 61

Take a look at 23:43 of the video you posted. You should do the view binding inside a DelayBind method.

this.DelayBind(() => {
    var set = this.CreateBindingSet<MyCustomControl, MyItemViewModel>();

    set.Bind(badgeLabel).For(v => v.Text).To(x => x.BadgeText);
    set.Bind(topSummary).For(v => v.Text).To(x => x.TopSummary);
    set.Bind(bottomSummary).For(v => v.Text).To(x => x.BottomSummary);

    set.Bind(this.Tap()).For(v => v.Command).To(x => x.Edit);
    set.Apply();
});

MvvmCross will do the binding for you. Also Mind that the proper types have to be passed to CreateBindingSet.

On a side node, MvvmCross N+1 videos are from 2013 and some things has changed since then. You can find some good examples there but sometimes it just won't work anymore.

If you are new to MvvmCross, download the source code of Playground project for reference:

https://github.com/MvvmCross/MvvmCross/tree/develop/Projects/Playground

and join the #mvvmcross slack channel if you need more help

https://xamarinchat.herokuapp.com/

MvvmCross is really great... once you grasp the basic concepts.

Upvotes: 1

Related Questions