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?
2 Answers
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.
-
Good to know you got it sorted. Goodluck! – Mohib Sheth Jul 19 '13 at 05:25
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.

- 1,135
- 10
- 22
-
-
I am still struck on this issue. I was looking at this article: http://stackoverflow.com/questions/16724278/mvvmcross-for-android-how-to-do-binding-in-code. The problem that I am facing is that I am not able to get the method CreateBindingSet(). Currently my activity inherits from MvxActivity. Am I missing some assembly reference or namespace. – Amit Jul 18 '13 at 22:20
-
Thanks for the link to the video. The part where Mr. Stuart mentions you can have multiple view models was helpful. – Elijah Lofgren Dec 09 '17 at 19:29