WPF Get parent window

user2644964 picture user2644964 · Apr 4, 2014 · Viewed 49.7k times · Source

Hy,

In my MainWindow.xaml.cs file I made a getter to get the reference to my listbox.

public ListBox LoggerList
{
    get { return Logger; }
}    

Now I want to access the LoggerList from a normal class but I don't work. I tried the following:

MainWindow parentWindow = Window.GetWindow(this) as MainWindow;
object selectedItem = parentWindow.LoggerList;

But this only works in a *xaml.cs file and not in a normal *.cs file.

Best regards

Answer

Sheridan picture Sheridan · Apr 4, 2014

There are a number of ways of accessing Windows in WPF. If you have several open, then you can iterate through them like this:

foreach (Window window in Application.Current.Windows) window.Close();

If you had a particular type of custom Window, you could use this:

foreach (Window window in Application.Current.Windows.OfType<YourCustomWindow>()) 
    ((YourCustomWindow)window).DoSomething();

If you are just after a reference to the MainWindow, then you can simply use this:

Window mainWindow = Application.Current.MainWindow;

However, using this method, there is a chance that it will return null. In this case, make sure that you set the MainWindow to this property in it's constructor:

// From inside MainWindow.xaml.cs
Application.Current.MainWindow = this;

It should be noted however, that @woutervs is correct... you should not be accessing UI controls from Windows in library classes. You really should data bind collections to the ListBox.ItemsSource and then manipulate the data collection instead.


UPDATE >>

I don't know why your Application.Current object is null... it could be because you've loaded your class library into a different AppDomain. Either way, I think that you are missing the big picture. There really is no reason why a class library class should need a reference to the main Window.

If you need to perform some work on the data collection, then just pass the data collection from code behind, or your view model. Once the work is complete, then just pass it back to the UI where you have access to the ListBox and/or the collection that is data bound to the ItemsSource property.