Valorem Consulting

| Tags: Silverlight, WPF

originally posted by Josh Smith: (link) - please comment at original post

One sorely missing feature from the Blend 4 Beta is the ability to have a method in which you can perform initialization work specific to design-time.  Such a method is useful for tasks like loading design-time data services into a container, configuring MEF with design-time specific dependencies, and basically anything else that you might otherwise do at startup when the application runs.  Since your App class won’t be started up when in design mode, it would be great if there was a way for Blend to call a method designated for that purpose at design-time.

I have been thinking about this a lot recently.  Initially I thought that Blend could provide an attribute that I could apply to a static method, and it would then invoke that decorated method before loading any Views.  That seemed like the best solution (and still does, in my opinion).  However, since Blend has no such attribute, I figured it was a moot point…until I realized that I could create my own attribute for the same purpose!

If you decorate an assembly with an attribute, that attribute must be instantiated when the assembly is inspected via reflection (which Blend most certainly does).  So, I simply created a custom attribute and applied it to my assembly.  In that attribute’s constructor, I check to see if it was loaded into design-time.  If it was, I then perform my initialization logic.  How simple!

Here’s the code I added to AssemblyInfo.cs in a project loaded by Blend 4 Beta:

I assume people might want to genericize this class a bit, but the basic idea is quite simple.  Perhaps adding a Type parameter for a class to instantiate would be better, so that the instantiated class could handle initialization.  That would leave the attribute very simple and reusable.  I’ll leave that up to you, if you care…

Here’s the code, for copy-and-paste purposes:

// In AssemblyInfo.cs
// Apply this attribute to the assembly so
// that it will be created when the assembly
// is loaded into memory.
[assembly: DesignTimeBootstrapper]

class DesignTimeBootstrapperAttribute
: Attribute
public DesignTimeBootstrapperAttribute()
var dep = new DependencyObject();
if (DesignerProperties.GetIsInDesignMode(dep))
// TODO: Design-time initialization…

Remember to please comment at original post: (link)

Happy coding!

2018 IdentityMine, Inc. Privacy Policy