$ cat "

Starting WPF Application with Window from another Assembly

"

When you create a WPF application you get the standard App.xaml and Window.xaml files. The App.xaml file has the StartupUri attribute set to Window.xaml. This is all well and fine, and if you rename Window.xaml or create another window that you want to use as the startup window you can simply modify the value of the StartupUri attribute.

If you are want to use a window defined in another assembly as the startup window it becomes a little trickier. The simplest way to accomplish this is to override the Application.OnStarupt method. In you override you can instantiate the window you want to show and then simply call Show() on it. For example:


public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
// Create an instance of the window that is located in another assembly
var customWindow = new CustomWindow();

customWindow.Show();
}
}

You could also create your own main method, and manually create and run your application.

The first step is to create your own main method is to change the Build Action property of your App.xaml file from ApplicationDefinition to Page, which stops Visual Studio from creating a main method for you. The second step is to add a main method to your App class:


public partial class App : Application
{
[STAThread]
public static void Main()
{
Application app = new Application();

// Create an instance of the window that is located in another assembly
var customWindow = new CustomWindow();

app.Run(customWindow);
}
}

Now you are all set. Compile, run and enjoy!

Written by Erik Öjebo 2009-10-18 19:26

    Comments