Home > Backend Development > C++ > How to Navigate Between Views in WPF MVVM Without External Frameworks?

How to Navigate Between Views in WPF MVVM Without External Frameworks?

Linda Hamilton
Release: 2025-01-26 20:26:11
Original
946 people have browsed it

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>
Copy after login

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>
Copy after login
From sub -view navigation view

<code class="language-csharp">ViewModel = new PersonViewModel();</code>
Copy after login
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>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template