How to navigate to another page with the click of a button that's already inside a page?

Viewed 997
  • I have a Window that contains a frame.
  • I have two pages, Page1 and Page2, and ... inside them, I have a Button.
  • When the Window is loaded the frame navigates to Page1.

I want the frame to navigate to Page2 by clicking on the Button in the Page1.


I tried to use MVVM:

That's the Window XAML.

<Window x:Class="MVVM_Course.Navigation">
    <Window.DataContext>
        <viewmodel:NavigationViewModel/>
    </Window.DataContext>
    <Grid>
        <Frame x:Name="frame" Content="{Binding Page, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
    </Grid>
</Window>

The Window ViewModel:

public class NavigationViewModel
{
    private static object page;
    public static object Page { get { return page; } set { page = value; } }

    public static void ChangePage(object objpage){Page = objpage;}

    public NavigationViewModel()
    {
        ChangePage(new Page1());
    }
}

The Page1 XAML:

<Page x:Class="MVVM_Course.Page1">
    <Page.DataContext>
        <vm:Page1ViewModel/>
    </Page.DataContext>
    <Grid>
        <Button x:Name="btnGoTo2" FontSize="50" Command="{Binding BtnPage2Command}" Content="Go to Page 2"/>
    </Grid>
</Page>

The Page1 ViewModel:

class Page1ViewModel
{
    private ICommand btnPage2Command;
    public ICommand BtnPage2Command { get { return btnPage2Command; } set { btnPage2Command = value; } }
    public Page1ViewModel()
    {
        BtnPage2Command = new RelayCommand(GoToPage2);
    }
    private void GoToPage2(object obj)
    {
        NavigationViewModel.ChangePage(new Page2());
    }
}

When I compile, the frame navigates to Page1 but clicking on the Button does not change the Page. Using the debugging red circle tool it seems to be working, the property "Page" in NavigationViewModel changes from Page1 to Page2 but... the result is that nothing actually happens in the UI.

0 Answers
Related