Hook into ContentControl view creation

Topics: Conventions, Extensibility
Feb 17, 2014 at 8:21 PM
I am trying to add a generic permission based security mechanism to my app. What I would like to do is when the view gets created, bind IsReadOnly and Visibility properties to the results of my permission service. I can easily hook into the CreateWindow to do this if my view is a main window (i.e. created from ShowWindow). What I can't figure out is how (if at all) I can put the same logic into wherever it is that ContentControls get created and bound.

I suppose I can search through the ShowWindow's visual tree and look for ContentControls and do it there, but it seems like there might be a better way.

Thanks for the help,
Feb 18, 2014 at 8:01 AM
The simplest way is to re-define the View generation callback: ViewLocator.GetOrCreateViewType:
var baseGetOrCreateViewType = ViewLocator.GetOrCreateViewType;
ViewLocator.GetOrCreateViewType = (type, displayLocation, context) =>
                                                            var view = baseGetOrCreateViewType(type, displayLocation, context);
                                                            //... add your custom code to the view...
                                                            return view;
Such function is invoked every time a view is generated. On a side note: there is an high chance that you still need the custom code in CreateWindow, since a view that has to be displayed in a separate window, is forcefully wrapped inside a Window control, generated by the IWindowManager.