How to Compile a WPF Application as a Class Library

25
Jun
2009

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
{
    [STAThread]
    public static void Main()
    {
        var app = new Program();
        app.Run();
    }

    protected override void OnStartup(StartupEventArgs args)
    {
        base.OnStartup(args);

        var window = new PreCodeWindow(new PreCodeSettings(), PreCodeWindow.Mode.StandAlone);
        window.ShowDialog();
        if (window.DialogResult.HasValue && window.DialogResult.Value)
        {
            System.Diagnostics.Debug.WriteLine("OK");
            Clipboard.SetText(window.Code);
        }
        else
        {
            System.Diagnostics.Debug.WriteLine("Not OK");
        }        
    }
}

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.

Category: 

Comments

Follow the below link http://translate.google.com/translate?hl=en&sl=es&u=http://geeks.ms/blogs/etomas/archive/2008/10/14/wpf-library-project-file-cannot-specify-applicationdefinition-element.aspx&ei=iP1dSvXfA9PEmQeWs51_&sa=X&oi=translate&resnum=7&ct=result&prev=/search%3Fq%3DLibrary%2Bproject%2Bfile%2Bcannot%2Bspecify%2BApplicationDefinition%2Belement.%26hl%3Den%26safe%3Doff%26client%3Dfirefox-a%26channel%3Ds%26rls%3Dorg.mozilla:en-US:official%26hs%3Duem