How to Compile a WPF Application as a Class Library

Submitted on Jun 24, 2009, 11:17 p.m.

Charles Petzold’s book, Applications = Code + Markup - received some critical press for not being very pretty. And it’s true that there’s a lot of text and code listings but (and as you’ll see below), he was methodical.

I recently wanted to upgrade a Windows Live Writer plug-in I’d written to use the Windows Presentation Framework (WPF) – instead of WinForms and a custom UI library.

However my first attempt to compile the application as a Class Library resulted in the following error…

“Library project file cannot specify ApplicationDefinition element”.

Thankfully I’d remembered the opening chapters of Charles’ book where he spent considerable time explaining the creation of the application class and initial window. The trick in this case is to remove the App.xaml file. You then need to create your own start-up class – like Program.cs – as shown below, and the application will compile fine as either a Windows Application or Class Library. In the example below extra parameters are passed to the constructor of the main window which is opened as a Dialog – and then checked for the DialogResult value when the window is closed.

1public class Program : Application
3 [STAThread]
4 public static void Main()
5 {
6 var app = new Program();
7 app.Run();
8 }
10 protected override void OnStartup(StartupEventArgs args)
11 {
12 base.OnStartup(args);
14 var window = new PreCodeWindow(new PreCodeSettings(), PreCodeWindow.Mode.StandAlone);
15 window.ShowDialog();
16 if (window.DialogResult.HasValue && window.DialogResult.Value)
17 {
18 System.Diagnostics.Debug.WriteLine("OK");
19 Clipboard.SetText(window.Code);
20 }
21 else
22 {
23 System.Diagnostics.Debug.WriteLine("Not OK");
24 }
25 }

The downside to this approach is that you no longer have an application level location for placing resource dictionaries and other shared objects - and so these will need to be placed in each window as required.