How to Compile a WPF Application as a Class Library
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. public class Program : Application
public static void Main()
var app = new Program();
protected override void OnStartup(StartupEventArgs args)
var window = new PreCodeWindow(new PreCodeSettings(), PreCodeWindow.Mode.StandAlone);
if (window.DialogResult.HasValue && window.DialogResult.Value)
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.