A couple of months ago I was faced with the following hacking challenge:
One of our entities has pairs of properties: StreetName and StreetNameAdv, City and CityAdv, Name and NameAdv, … For each of these pairs, the screen should clearly color the background of the xx property, if the value does not match the xxAdv property.
If you happen to be familiar with the LightSwitch MVVM implementation, you’ll realize this is not a walk in the park, because the controls that form the View layer are tucked away in a LightSwitch theme extension. Trust me, that’s one area you’ll want to stay away from unless you’re really experienced with LightSwitch extensibility.
So the easier way, in this case… Is to break our MVVM layering…
Breaking MVVM: episode one: Finding ViewModel ContentItems bound to a particular property on the Model.
This code snippet contains an extension method to track all ContentItems that are displaying a particular property. The first step is to retrieve an IScreenPresentationView from an IScreenObject. We do this with the help of the ScreenViewService, a class intended to help out people with their custom shells. From there, it’s a recursive walk down the children of this root, and find out who’s displaying what.
Breaking MVVM: episode two: Finding ContentPresenters and their controls.
Once you have a ContentItem, it’s a walk in the park to get all associated presenters (the’View’ layer): call the GetAssociatedPresenters method.
Almost there. What you have now is a bunch of IContentItemPresenters, which give you access to the Silverlight controls used by your selected LightSwitch theme via their .Visual property. However, these Silverlight controls are usually a lot more complex than a mere ‘TextBox’ or ‘Label’ here and there. Hence, you’ll have to take a recursive dive in the visual tree to find the real control you need to color:
Mission accomplished! Well, these code snippets are really only the ‘helper methods’ to help you break your MVVM layering. Depending on your needs, you’ll need some additional code. I have a sample that demonstrates the entire thing in action. Feel free to grab it from my skydrive!
Keep rocking LS!