View navigation in the WPF mvvm application
In the WPF MVVM application, the view navigation involves the DataContext of ContentControl to set the corresponding viewmodel. By binding ContentControl to the ViewModel attribute of the parent ViewModel, you can easily switch the view in the ViewModel.
Create the base class ViewModel
Define a base class for your ViewModel, such as BaseViewModel, which contains public attributes and interfaces, such as inotifypropertychanged. This base will provide a public structure for all ViewModels.
Create data binding in the app.xaml
In the app.xaml file, it specifies the datatemplate that connects the view to its corresponding ViewModel. For example:
<code class="language-xml"><DataTemplate DataType="{x:Type ViewModels:MainViewModel}"> <MainView/> </DataTemplate></code>
Display view
In your mainwindow.xaml, use ContentControl to display the current viewmodel:
<code class="language-csharp">public BaseViewModel ViewModel { get; set; }</code>
From sub -view navigation
From the sub -view navigation to another view, add the binding in the sub -view to the command in the mainViewModel. For example:
<code class="language-xml"><ContentControl Content="{Binding ViewModel}"/></code>
<code class="language-xml"><!-- 省略子视图中的绑定示例,因为原文未提供 --></code>
The above is the detailed content of How to Navigate Between Views in a WPF MVVM Application?. For more information, please follow other related articles on the PHP Chinese website!