1

Page Navigation in WPF MVVM

Posted by Nantharupan on 3:02 AM in , ,
When i tried to follow MVVM architecture in WPF, i faced the challenge of how to do Navigation to pages in Frame. finally i figured it out in the internet.

You need to have  a navigator class like following,
public class Navigator
{
public static NavigationService NavigationService { get; set; }
public static void Cancel()
{
MessageBoxResult result = MessageBox.Show("Are you sure you want to cancel?", "Cancel",MessageBoxButton.YesNo);
if (result == MessageBoxResult.Yes)
App.Current.Shutdown(1);
}
}
view raw gistfile1.txt hosted with ❤ by GitHub



In your App.xml.cs file under the OnStartup method put the following code



MainWindowViewModel vm = new MainWindowViewModel(); // Your View Model for the Main Page
MainWindow main = new MainWindow();
Navigator.NavigationService = main.NavigationFrame.NavigationService;
main.DataContext = vm; // Set the Data Context for your Window
main.Show(); // Show the page
// Load and navigate to the first page
Page1ViewModel pagevm = new Page1ViewModel(); // Your View Model for page in the Fram
Page1 p1 = new Page1(); // Your page to be in the Frame
p1.DataContext = pagevm; // Set the Data Context for your page
Navigator.NavigationService.Navigate(p1); // Call Navigate to the page
view raw gistfile1.txt hosted with ❤ by GitHub


Now you can call any pages in the ViewModel like the code follows
Navigator.NavigationService.Navigate(new Uri("Views/CashTransactions.xaml", UriKind.Relative));
view raw gistfile1.txt hosted with ❤ by GitHub


Happy Coding



1 Comments


Hi Thanks for your valuable post. COuld you please share the complete project.

Post a Comment

Popular posts

Copyright © 2009 On the way All rights reserved. Theme by Laptop Geek. | Bloggerized by FalconHive.