-1

I have a window named 'mainWindow' with two frames named 'mainFrame','sidepanel' and in 'mainWindow', when I click 'btn1' from 'sidepanel', 'mainFrame' is navigated to 'frame1' which is a Page. In 'frame1', I have a Border control as only child.

mainWindow.xaml.cs:

((mainWindow)App.Current.MainWindow).mainFrame.Navigate(new frame1());

frame1.xaml:

<Border>
</Border>

frame1.xaml.cs:

public frame1()
{
    InitializeComponent();
    var page = ((mainWindow)App.Current.MainWindow).mainFrame.Content as Page;
    var border = page.Content as Border;
}

I'm having "System.NullReferenceException" when initializing border as page.Content=null. But if I click 'btn1' for the 2nd time, it is initialized with 'System.Windows.Controls.Border'. But I want this result when I click 'btn1' for the 1st time.

Please, help me with a good solution.

swapnil saha
  • 1,220
  • 10
  • 10
  • It's not directly related to the issue, but isn't `((mainWindow)App.Current.MainWindow).mainFrame.Content` supposed to be `frame1`? Save yourself the pain and call directly `this.Content` – Kevin Gosse Aug 08 '16 at 09:46
  • 2
    As for the issue itself, it's likely that you're trying to access the content too early in the page lifecycle. Try moving your code inside of the `Loaded` event – Kevin Gosse Aug 08 '16 at 09:48

1 Answers1

0

As @KooKiz suggested, this one gave me the solution:

frame1.xaml.cs:

private void Page_Loaded(object sender, RoutedEventArgs e)
{
    var page = ((mainWindow)App.Current.MainWindow).mainFrame.Content as Page;
    var border = page.Content as Border;
}

frame1.xaml:

<Page Loaded="Page_Loaded">
    <Border></Border>
</Page>
swapnil saha
  • 1,220
  • 10
  • 10