Skip to content

Accessing the Application object in a WPF application

September 7, 2006

When building a web application, developers often need to share state from page1 to page2.  There are many techniques to do that, but none are very elegant.  Cookies, hidden IFrames, store all the state on the server, etc…

WPF applications have an object that is running all the time during your application, the Application object.  Each of your Windows or Pages can share state with Application.Properties or via new Properties or Methods you define yourself in the code behind file for App.xaml.

How do you find the Application object?

Via a static property on the Application class named Current.  Here we find the Properties collection on the application object and add a new setting.  This feels similar to Session variables in ASP.NET.

VB:    App.Current.Properties("myProp") = 5
C#:    App.Current.Properties["myProp"] = 5;

Note: Application.Current works as well.  App works if App is the name of the class defined in App.xaml (which is usually the default.)

How do you find your enhanced version of the Application object?

In the code behind file for App.xaml (app.xaml.vb, app.xaml.cs, etc…), you can add functionality to a custom version of the Application object.  You can then set properties or call methods on that object from any Window/Page.

    dim MyApplication as App = CType(App.Current, App)
    MyApplication .MyCustomMethod(foo)
    App MyApplication = ((App)Application.Current);
    MyApplication .MyCustomMethod(foo);

CTP Note

Preview versions of WPF/"Avalon" used to automatically generate a MyApplication property that was equivalent to MyApplication in the sample above.  If you are migrating old code, you now need to define MyApplication yourself.

Related Resources

SDK Documenation:


From → WPF

One Comment
  1. Unknown permalink

    Telechargemet les applications

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: