0

I have MainWindow and User Controls inside each Tab. When I am switching too fast between tabs or sometimes even without switching I get null in main;

var main = UIHelper.FindVisualParent<MainWindow>(this);

Why does this happens do you know? Let's say it shows error such as main is null once in 7-10 tries. I am using it in User Controls to get access to controls of MainWindow. Thanks in advance.

Firdavs Kurbonov
  • 1,252
  • 4
  • 16
  • 42
  • 1
    In this special case I would use `var main = Application.Current.MainWindow;` to get MainWindow. – LPL Jun 17 '13 at 12:43
  • 2
    You have to wait till your UserControl has been added to the VisualTree i.e. after the Template has been applied....so that you can then navigate up the hierarchy...see here: http://stackoverflow.com/questions/10768945/wpf-force-to-build-visual-tree – Colin Smith Jun 17 '13 at 12:44
  • @LPL It did not return anything in my case. I used it. – Firdavs Kurbonov Jun 17 '13 at 12:48
  • [Application.MainWindow Property](http://msdn.microsoft.com/en-us/library/system.windows.application.mainwindow.aspx) should give you "a reference to the first Window object to be instantiated in the AppDomain." – LPL Jun 17 '13 at 12:54

1 Answers1

2

You have to wait till your UserControl has been added to the VisualTree i.e. after the Template has been applied....the easiest way to do that is wait till the Loaded event has been fired.

Then you can safely navigate up the hierarchy and look for your MainWindow.

Bear in mind though, that with the TabControl when you switch tabs, the tabs that disappear will unload their Visual content.

Thus you might need to watch the Unloaded event on your UserControl to ensure you don't call VisualTreeHelper when you are no longer in the VisualTree.

If you want to prevent the unload behaviour then you can modify the TabControl behaviour...but the original TabControl is designed like that to efficiently create visuals.

Community
  • 1
  • 1
Colin Smith
  • 12,375
  • 4
  • 39
  • 47