29

How can I access, using C#, a public instance method declared in App.xaml.cs?

RandomEngy
  • 14,931
  • 5
  • 70
  • 113
Gus Cavalcanti
  • 10,527
  • 23
  • 71
  • 104

3 Answers3

75
((App)Application.Current).YourMethod ....
Akash Kava
  • 39,066
  • 20
  • 121
  • 167
  • It works, but I don't understand. If Application.Current == App, and they are the same type, how is this type-cast working? Thanks – Gus Cavalcanti Oct 22 '09 at 18:58
  • 2
    Application is System.Windows.Application where else App is inside your project derived from Application, Application.Current is of type Application, not App. – Akash Kava Oct 22 '09 at 19:08
  • 1
    Thanks. Is it possible to do this right from a xaml-view ? (Like _Click="App.YourMethod"_) – mYnDstrEAm Oct 10 '14 at 12:26
4

Have you considered to create a separate class to hold your application wide methods (eg. AppState.cs)?

thomasmartinsen
  • 1,983
  • 14
  • 21
  • This is a better approach, but I wanted to know how to see the stuff declared in App.xaml.cs. Thanks. – Gus Cavalcanti Oct 22 '09 at 18:56
  • 7
    I'm curious what you had in mind with this suggestion. You still need a place to store it. Where better to store an application-wide method than in your application class? How else would you be able to access it from any window? – Jonathan Wood Jun 22 '16 at 17:00
0

You can also add a static property in your App class with new modifier like so:

public static new App Current => Application.Current as App;

This way you can access your method like so:

App.Current.YourMethod()

Check this answer about new modifier on SO.

Robert
  • 2,407
  • 1
  • 24
  • 35