1
Page Navigation in WPF MVVM
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.
Happy Coding
You need to have a navigator class like following,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
In your App.xml.cs file under the OnStartup method put the following code
Now you can call any pages in the ViewModel like the code follows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Navigator.NavigationService.Navigate(new Uri("Views/CashTransactions.xaml", UriKind.Relative)); |