Freigeben über


Share sourcecode between Silverlight and WPF Applications

Sharing code between Silverlight and WPF Applications has been a returning wish from several of the customers in our Microsoft Innovation Center in Denmark. The base class libraries are very similar, but obviously something is missing in the 3-4 MB Silverlight download you just installed on that iMac in your girlfriends officespace... therefore if you use features in .NET that is not supported by the SL BCL sharing is not possible. As you are compiling your projects to a given runtime the binary sharing is not really an option either. That leaves us with source code sharing - which is close to 100% better than no sharing at all.

Code to share typically include Presentation Models, Controllers, Domain Objects, Data Transfer Objects etc.

It is a good idea to start with the lowest denominator (Silverlight) if you have the choice from the beginning of your project. Some limitations may require you to think completely differently than you would normally if you were starting out with the full featureset of WPF (ex. ICommand) - you will eventually run into grayzones and I will leave it up to your judgement to decide when and how much you can/should share.

One way to achieve code file sharing is to use the "Add As Link" in the "Add Existing Item" dialog in Visual Studio (push the little arrow to get to it)

image

An example is shown below:

image

Notice the "link" icon on the "MyClass.cs" file in the Silverlight project.

If you have code that is not really shared but nice to keep in the shared file you can make use of the C# preprocessor directives. That sounds like a bad thing to do, but you may have to use different namespaces etc. Silverlight projects actually has a SILVERLIGHT "define" allowing you to include specific code simply by writing:

#if SILVERLIGHT
using System.Windows.Media.Animation;
#endif

You will notice that this is grayed out in the FullCLR project (and obviously the directive #if !SILVERLIGHT may be used in the opposite case)

I have just learned about another way of sharing source files that is less visible in the UI (no "linked icon") but seem to solve the exact same problem.

Any comments and other ideas are welcome - i acknowledge that it is kind of simple but it solves most cases where source code sharing is possible.

Comments