Domanda

I have a non static class MainWindow that contains two non-static methods ShowAskAQuestionDialog() and ShowTechSupportForum(). I am calling these methods from a different window that opens from an instance of MainWindow. How do I use this instance of MainWindow to call these two methods? I tried doing this...

            MainWindow mainWindow = (MainWindow)this.Owner;
            mainWindow.ShowAskAQuestionDialog();

But I guess MainWindow is not actually the owner of the new window that opens from it.

Is there any way to reference that instance of MainWindow?

I know I could do something LINQ related like

var windows = Application.Current.Windows
                                 .OfType<Window>()
                                 .Where(x => x.GetType() != typeof(MainWindow)

But I was hoping there is something like this.Parent or this.Previous, something where there would be no possibility of also selecting a stray instance of MainWindow

È stato utile?

Soluzione

If MainWindow is your startup window, you can get it using Application.Current.MainWindow.

Since MainWindow will return instance of Window, you need to typecast it back to MainWindow:

MainWindow window = (MainWindow)Application.Current.MainWindow;

Altri suggerimenti

Create a static variable on MainWindow named Instance, set it in the constructor. Now you have a handle to it.

private static MainWindow _instance;

public static Instance
{
   get{  return _instance; }
}

In the constructor of MainWindow, add this:

_instance = this;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top