Multiple pages per frame? do not update. What am I missing?

So here is the script. I have 3 xaml :

  • Mainwindow
  • Page1
  • Page2

In MainWindow, I have a button named "Page1" and a frame named "Frame1"

code:

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1. Dim page1 As New Page1 Frame1.Navigate(page1) End Sub 

Thus, it will display Page1.xaml in "Frame1"

Then under Page1.xaml I have another button named " Page1.xaml "

code:

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click Dim p2 As New page2 Dim main As New MainWindow main.Frame1.Navigate(p2) End Sub 

The frame will not cause any changes when the button is pressed inside "Page1", which is located inside "Frame1" and inside "MainWindow"

I think something is missing ...

+4
source share
1 answer

Basically, your problem is that you are creating a new main window in the event with the button 1 pressed, and not referring to the existing main window. Therefore, when you actually call the Frame1 Navigate method, you actually do it in a completely different window that just becomes invisible.

What you need to do is find the link to the MainWindow main page. There are several ways to do this.

  • You can use a routed event and pick it up from Page1 and process it with your MainWindow.
  • You create a public property on page 1 and pass it your instance of MainWindow when you create the page.
  • You can also scan the visual tree, starting on page 1, until you find MainWindow, and then navigate. I will demonstrate this in the code below.

XAML For Page 1

 <Page x:Class="WpfApplication1.Page1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" Title="Page1"> <Grid> <Button HorizontalAlignment="Center" VerticalAlignment="Bottom" Click="Page2Button_Click" Content="Page 2" /> </Grid> </Page> 

Code-Behind for Page 1

 using System.Windows; using System.Windows.Media; namespace WpfApplication1 { /// <summary> /// Interaction logic for Page1.xaml /// </summary> public partial class Page1 { public Page1() { InitializeComponent(); } private void Page2Button_Click(object sender, RoutedEventArgs e) { var mainWindow = GetParentWindow(this); if (mainWindow != null) mainWindow.Frame1.Navigate(new Page2()); } private static MainWindow GetParentWindow(DependencyObject obj) { while (obj != null) { var mainWindow = obj as MainWindow; if (mainWindow != null) return mainWindow; obj = VisualTreeHelper.GetParent(obj); } return null; } } } 
0
source

All Articles