Home >Backend Development >C++ >How to Navigate Between Views in WPF MVVM Without External Frameworks?
WPF MVVM view navigation without external framework
In WPF applications that manage multiple views using MVVM mode, navigation between views is crucial. This article will solve the problem of switching to another in one view, especially after navigation from view 1, view 2 loaded to the same window.
Unlike those reference links that use MVVM Light or other frameworks, a simplified, no need to rely on external dependencies is provided here. This method uses a data template to associate the view with the view model and use the ContentControl to display the selected view.
Data template and viewmodel bind
In resources such as app.xaml, define the data template to map the view model to its corresponding view:
Switching the view from the main ViewModel
<code class="language-xml"><DataTemplate DataType="{x:Type ViewModels:MainViewModel}"><MainView /></DataTemplate> ...</code>
In the mainViewModel, create a ViewModel attribute, which can be set to different view models:
To switch to another view, just allocate the corresponding view model to this attribute:
<code class="language-csharp">public BaseViewModel ViewModel { get; set; }</code>From sub -view navigation view
<code class="language-csharp">ViewModel = new PersonViewModel();</code>In order to be able to navigate from the sub -view, declare a command in MainViewModel:
In the sub -view XAML, bind the Command property of the button to this ICommand:
By following these steps, you can effectively navigate the view view in WPF MVVM applications to ensure a smooth user experience.
<code class="language-csharp">public ICommand DisplayPersonView { get { return new RelayCommand(action => { ViewModel = new PersonViewModel(); }, canExecute => { ... }); } }</code>
The above is the detailed content of How to Navigate Between Views in WPF MVVM Without External Frameworks?. For more information, please follow other related articles on the PHP Chinese website!