View navigation in the WPF MVVM application allows switch between different user interfaces. This article explores a simple way to achieve navigation without relying on frameworks such as MVVM LIGHT.
Set the view model
Create a base view model class, define public attributes and interfaces. Each specific view model (for example,
,, INotifyPropertyChanged
) should inherit the self -based class. MainViewModel
PersonViewModel
Connect the view to the view model CompanyViewModel
In , the data template associated with the view model will be declared. This will present the corresponding view based on the specified view model.
App.xaml
In the main view, use
attributes to display different views. Modify the view model to switch the displayed view. From sub -view navigation
ViewModel
To navigate from the sub -view, create a command in the main view model and bind it to the button in the sub -view. When this command is executed, the command will change the ContentControl
attribute in the main view model, thereby triggering view switching.
code example
BaseViewModel: ViewModel
app.xaml (datatemplates):
<code class="language-csharp">public class BaseViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; }</code>
Please note that this example requires the implementation of the
<code class="language-csharp">public class MainViewModel : BaseViewModel { private BaseViewModel viewModel; public BaseViewModel ViewModel { get { return viewModel; } set { viewModel = value; OnPropertyChanged(nameof(ViewModel)); } } public ICommand DisplayPersonView { get; } public MainViewModel() { DisplayPersonView = new RelayCommand(() => ViewModel = new PersonViewModel()); } protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class RelayCommand : ICommand { private readonly Action execute; public event EventHandler CanExecuteChanged; public RelayCommand(Action execute) { this.execute = execute; } public bool CanExecute(object parameter) => true; public void Execute(object parameter) => execute(); }</code>
class. Methods and Class need to be adjusted or replaced according to your actual situation. prefix represents your view name space. Make sure your view and view model is correctly defined and associated.
The above is the detailed content of How to Implement Simple View Navigation in WPF MVVM without External Frameworks?. For more information, please follow other related articles on the PHP Chinese website!