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:

It not only keeps it working but you can use the technique to put mocks into the designer. Very handy.

Need Your Help

ObjectListView Not Showing Selection Color For Selected Item

c# winforms listview objectlistview

I have an ObjectListView which is essentially a wrapper around the standard .NET ListView. My problem is that I cannot figure out the correct sequence of method calls to add a new object to the co...

Jquery or Javascript tracing for events and other actions

jquery jquery-plugins javascript-events javascript

i have many javascript or jquery methods in my proect. 85%+ is client side scripting. I haev Jquery validate and Labelify plugins. Hence, whenever i make changes in Jquery methods or Javasc...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.