Reputation: 1170
On a C# application that I am working on, I have a frame on my main window.
<Frame x:Name="frame" Grid.Column="1" Grid.Row="0" Grid.RowSpan="2" NavigationUIVisibility="Hidden"/>
I click a button on my main window, and then I use the frame that I created to navigate to a page using the code below.
//Create a new object for the page
CameraPage camera = new CameraPage();
//Navigate to the new page
frame.NavigationService.Navigate(camera);
What I would like to do is if I click a button on the camera page that is contained within the frame, then it only exits the page while still keeping the main window intact.
I have tried something like this.
NavigationService.GoBack();
But then I get an error:
System.InvalidOperationException: 'Cannot navigate because there is no entry in the Back stack of the journal.'
I believe this error is happening because the navigation stack I used to go the page is apart of the main window code and not the page that I navigated to.
So my question really is, how do I close a page contained within a frame with a button contained within the page, without closing the entire application?
Upvotes: 1
Views: 2570
Reputation: 6734
If you want to end up with an empty Frame
again, all you have to do is clear the Frame
's contents. According to this answer, you can do so like this:
frame.Content = null;
That will get you back to how things started, now you just to trigger it. For that, I'll refer you to the question WPF Frame and Page Get event. The answer there shows you how to use DelegateCommand
(a.k.a. RelayCommand
) to accomplish this. This is the way I would go, because it keeps the Page
nice and separate from whatever Window
is hosting it.
Technically, you could also pass your Page
a reference to frame
when you initialize it, then have it set frame.Content = null;
that way. But that's a sort of "quick and dirty" approach, not really a best practice.
Upvotes: 1