Quantcast
Channel: Redino blog
Viewing all articles
Browse latest Browse all 80

WPF Set StartupUri in code

$
0
0

Introduction

StartupUri is a property of Application class, which sets the first UI to show when application starts. By default it’s set in App.xaml file, e.g.

<Application x:Class="MEFCalculator.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">

In above code the StartupUri value is MainWindow.xaml, and using default value is OK for most of times.

 

Why Set StartupUri in Code?

But what if you want to show other windows according to different conditions? Assume our application can open .proj files, so the file name will be passed in as command line arguments.  Now we want to show a file chooser dialog at startup if user run our application directly (without double clicking .proj files), and open another window (call it Project Explorer) when user start application by double clicking .proj file.

In this case we need to check command line arguments, then set corresponding StartupUri in code.

 

How to Do it

First in App.xaml.cs, add an override method OnStartup for Application class.

protected override void OnStartup(StartupEventArgs e)
{
     
}

This method will be called at startup of application.

 

Next we set the StartupUri according to whether filename is passed in.

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    String[] args = System.Environment.GetCommandLineArgs();
    // opened by double clicking project file (passed in filename as command line arguments)
    if (args.Length > 1)
    {
            this.StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);
    }
    // open application directly
    else
    {
            this.StartupUri = new Uri("UI/Windows/DashboardWindow.xaml", UriKind.Relative);
    }
}

In above code we call System.Environment.GetCommandLineArgs method to get command line arguments. You can see the StartupUri is actually an Uri object, its UriKind is UriKind.Relative. (If we don’t specify the UriKind parameter, we will get an UriFormatException)

 

 

The post WPF Set StartupUri in code appeared first on Redino blog.


Viewing all articles
Browse latest Browse all 80

Trending Articles