ViewLocator customization

Topics: Bootstrappers & IoC, Extensibility
Dec 1, 2011 at 9:36 AM


I have question. I am writing Silverlight application and I want to be able to change my views without recompiling the application. My idea is to have xaml files on the disk drive and fetch them over the network on demand. If I figured out correctly I need to customize ViewLocator. I am not sure about feasibility of my idea but I want to give it a try. I need suggestion of how to customize/replace ViewLocator?

Thank you



Dec 4, 2011 at 9:49 PM

You need to extend/replace at least one of the three Functions on the ViewLocator:

  • Func<Type, DependencyObject, object, Type> LocateTypeForModelType: This takes the vm type, display location and context and returns the type of the view
  • Func<Type, DependencyObject, object, UIElement> LocateForModelType: This takes the same parameters as before but returns a view instance
  • Func<object, DependencyObject, object, UIElement> LocateForModel: this takes the instance of the vm instead of the type as parameter. rest is the same as before.

For your idea the first one fits best. You can store a mapping from vm type to view type in xml and do a lookup in the mapping when a view is requested. When a match is found, you return the type from the mapping. When no match is found you simply reuse the base behavior

Dec 6, 2011 at 8:29 AM

Thank you very much for reply.

Only way that I see to do what you suggested is to change source and compile Caliburn.Micro. Is there a way to create a new ViewLocator and configure Caliburn to use newly created ViewLocator class?


Dec 6, 2011 at 8:38 AM

The Functions are exposed as properties on the view locator, not methods. you can simply replace them


var defaultLocate = ViewLocator.LocateTypeForModelType;
var myLocate = (vmType, location, context) => 
    if (mappings.Keys.Containts(vmType))
        // the new stuff
    } else
        return defaultLocate(vmType,location,context)
ViewLocator.LocateTypeForModelType = myLocate;

Dec 9, 2011 at 5:07 AM

You don't have to override the entire transformation function. You just need to had a new rule. Can you give examples of the exact name transformations that you'd want?