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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With