How do you get the WPF / XAML designer to work with custom classes with dependencies?
I'm using a custom class to perform validation in a WPF app and have defined a class which inherits from ValidationRule. The class has a dependancy which I would like AutoFac to inject at runtime, but the Visual Studio 2010 XAML designer needs a parameterless constructor in order to work.
It seems the only solution is to create a DependencyProperty for the dependency and bind it in XAML, but that means the dependency is publicly accessible and mutable, neither of which I want.
Is there any way to pass a dependency in to a class you intend to use in XAML which will do all of the following?
- Not break the designer.
- Keep the dependency private.
- Make sure the dependency is set before the class is used.
How badly do you want to do it?
The features in XAML 2009 provide the following elements which could help you:
x:Arguments would allow you to pass an argument to the constructor. Can this argument be somehow bound to a property of your view model?
x:FactoryMethod allows you to specify the method which creates the object. I assume this can be a method of your window or usercontrol, which would have access to your dependency container.
But here's the problem: XAML 2009 can only be loaded at runtime via a XAML Reader, and can not be compiled. (See Can't get the new 2009 XAML primitives working, why?).
So global static objects (eurgh) might still be the less painful solution.
Later Edit: I reread your question, and realised you had put "Not break the designer" as one of you requirements. This excludes XAML 2009 from the possible solutions.
This is an excellent question. I used techniques demosontrated here to keep the designer working: http://jonas.follesoe.no/2008/07/24/youcard-re-visited-implementing-dependency-injection-in-silverlight/
It not only keeps it working but you can use the technique to put mocks into the designer. Very handy.