Amit
Amit

Reputation: 227

Does MvvmCross allow binding of ViewModel properties to controls created on the fly?

I have an application in which most of the controls are created in code and then added to the layout using AddView method. Does the framework allow binding of ViewModel properties to controls using code or it has to be done in the axml file only?

Upvotes: 6

Views: 2911

Answers (2)

Amit
Amit

Reputation: 227

Alright, after a lot of struggle I finally got the answer.

I had to do the following things.

1) Added an import statement :

using Cirrious.MvvmCross.Binding.BindingContext;

2) Added the following code:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.Hello);

    TableLayout containerLayout = this.FindViewById<TableLayout>(Resource.Id.containerLayout);
    if (containerLayout != null)
    {                          
        TableRow newRow = new TableRow(base.ApplicationContext);
        newRow.SetMinimumHeight(50);

        var txtRace = new EditText(ApplicationContext);
        txtRace.Hint = "Race";

        var bindingSet = this.CreateBindingSet<HelloView, HelloViewModel>();
        bindingSet.Bind(txtRace).To(vm => vm.Race);
        bindingSet.Apply();

        newRow.AddView(txtRace);
        containerLayout.AddView(newRow);
    }
}

I already have a "TableLayout" in my HelloView.axml file and all that I am doing in this is creating a new EditText box control (txtRace) and adding it to the view and at the same time binding it to the "Race" property of HelloViewModel object.

I spend a lot of time trying to figure out in what namespace CreateBindingSet() method exists because VS2012 was not giving me any intelliscence on that.

Hope this helps someone facing similar issue.

Upvotes: 10

Mohib Sheth
Mohib Sheth

Reputation: 1135

Yes MvvmCross supports binding properties to controls created at runtime. You can watch this tutorial by the awesome Mr. Stuart in his N+1 series. http://www.youtube.com/watch?feature=player_embedded&v=cYu_9rcAJU4

Note: He has shown this many a times in the series but I remember this one on the top of my head right now.

Upvotes: 2

Related Questions