How can I access, using C#, a public instance method declared in App.xaml.cs?
3 Answers
((App)Application.Current).YourMethod ....
-
It works, but I don't understand. If Application.Current == App, and they are the same type, how is this type-cast working? Thanks Oct 22, 2009 at 18:58
-
2Application is System.Windows.Application where else App is inside your project derived from Application, Application.Current is of type Application, not App. Oct 22, 2009 at 19:08
-
1Thanks. Is it possible to do this right from a xaml-view ? (Like Click="App.YourMethod") Oct 10, 2014 at 12:26
Have you considered to create a separate class to hold your application wide methods (eg. AppState.cs)?
-
This is a better approach, but I wanted to know how to see the stuff declared in App.xaml.cs. Thanks. Oct 22, 2009 at 18:56
-
7I'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? Jun 22, 2016 at 17:00
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.