Thursday, June 07, 2012

How to bind to a UIViewController instance Property in Monotouch MvvmCross


From reading your question, I think what you are saying is that the View itself has a field of type string...
Your code:
     new Dictionary()
          { StringTemp, "{'Text':{'Path':'AboutText'}}" },
is trying to bind the property Text on the object referred to by StringTemp to whatever is inAboutText on the ViewModel.

To set the StringTemp string itself you should be able to bind to it using something like:
      new Dictionary()
           { this, "{'StringTemp':{'Path':'AboutText'}}" },

Just to explain the parts in: { this, "{'StringTemp':{'Path':'AboutText'}}" }, these can be thought of as { TargetObject, "{'TargetPropertyName':{'Path':'SourcePropertyName'}}" } where:
  • TargetObject (this) is the object you are aiming to set property values on
  • TargetPropertyName (StringTemp) is the name property that you are aiming to set
  • SourcePropertyName (AboutText) is the name of the property that will be the source of the value
Note that Mvx uses Properties - not fields - so private string StringTemp {get;set;} is bindable, but private string StringTemp; is not.

You could also do two-way binding for this string reference if you wanted to... but you would need to setup some custom binding information to do so - there would need to be some event fired and captured in order to update the ViewModel (I'll leave that for another day!)

For situations where direct binding isn't what you are looking for, then you can always subscribe to PropertyChanged and handle the notifications in more verbose code... e.g.:
ViewModel.PropertyChanged += (s,e) => 
    if (e.PropertyName == "AboutText")
         // do something complicated here with the new ViewModel.AboutText value
...but I personally tend to avoid this type of code where I can...

No comments:

Post a Comment