Chris
Chris

Reputation: 1015

Access instance of class from MainWindow

I have an application with MainWindow and another class called MyClass. MyClass has a method in it that I need to access from the MainWindow class. MyClass is loaded when the application loads. How do I call the method in MyClass from MainWindow without creating a new instance of MyClass:

MyClass class = new MyClass();

?

Upvotes: 1

Views: 1226

Answers (2)

kyrylomyr
kyrylomyr

Reputation: 12632

The straight forward answer to your question is to mark class method as static. That will allow you calling it from any place.

On the other hand, it's probably is not what you really need. Thus, if you create MyClass on application start inside Application class then you need to expose MyClass instance, for example, through application property. Look at the example code.

public class MyClass
{
    public void Method()
    {
        // ...
    }
}

The code of your App:

public partial class App
{
    public MyClass MyClassInstance { get; private set; }

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        MyClassInstance = new MyClass();
    }
}

And the code of window where you call method of your class:

public partial class MainWindow : Window
{
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        ((App)Application.Current).MyClassInstance.Method();
    }
}

Upvotes: 2

Nick Freeman
Nick Freeman

Reputation: 1411

Sounds very suspect, but you do what you are saying by making that method static

public partial class MainWindow
{
    public void MethodInMainWindow()
    {
        // Don't need to create a new instance of MyClass
        MyClass.MethodInMyClass();
    }
}

public class MyClass
{
    public static void MethodInMyClass()
    {
        //  ....
    }
}

Here is a little bit of documentation on static vs instance

Upvotes: 0

Related Questions