WPF Get parent window

只愿长相守 提交于 2019-12-03 10:58:39

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!