Convention based binding - best extensibility point for traversing named elements

Dec 6, 2010 at 10:35 AM

Hi, I have a use case where I need to bind two elements on a view using conventions.  E.g, if I have an element called 'MyElementStatus', I need to strip off the 'Status' postfix, and find the element on the view called 'MyElement' and then do some binding between the two elements.  Looking at the viewmodel binder, it looks as though I need to traverse the namedElements, but I can't see an appropriate point of extensibility?

Dec 6, 2010 at 2:34 PM

You'll need to replace ViewModelBinder's BindProperties func with your own implementation. You can use the existing code as a template and just change the convention name mapping code to look for you custom patterns.

Dec 6, 2010 at 3:03 PM

Thanks Rob!

Dec 8, 2010 at 3:35 PM
Edited Dec 8, 2010 at 3:35 PM

Hi Rob,

I've managed to solve this by adding an additional element to the ViewModelBinder's BindProperties invocation list (setup in my bootstrappers Configure() method), rather than replace anything:

          ViewModelBinder.BindProperties += (namedElements, viewModelType) =>
                    var propertyStatusElements = namedElements.Where(e => e.GetType() == typeof(PropertyStatus));
                    foreach (var propertyStatusElement in propertyStatusElements)
                        var cleanName = propertyStatusElement.Name.Trim('_');
                        ApplyPropertyStatusBinding(namedElements, cleanName.Replace('_', '.'), propertyStatusElement);

This means I don't need to duplicate any code from the core BindProperties delegate.  It feels slightly dirty though! Did you intend it to be used this way??

Dec 8, 2010 at 3:56 PM

You know, I never thought of doing that...but it's a pretty cool idea. If it works, go with it :)