Bind WPF UI events (e.g. SelectionChanged) to ViewModel commands in MVVM
The MVVM pattern advocates separating UI logic from the data layer. For this reason, it is crucial to handle UI events in the ViewModel. In the provided code example, the SelectionChanged event is handled in code-behind. Let's explore how to move this event to the ViewModel.
Bind UI events to commands
WPF provides a powerful feature called data binding. It allows you to bind UI elements to properties or commands in the ViewModel. In this example, we're binding the contactsList's SelectionChanged event to a command in the ViewModel.
Use EventTriggers and InvokeCommandAction
To do this, you can use EventTrigger and InvokeCommandAction from the Windows.Interactivity namespace. An example is as follows:
<code class="language-xml"><ListBox ...> <i:Interaction.Triggers> <i:EventTrigger EventName="SelectionChanged"> <i:InvokeCommandAction Command="{Binding SelectedItemChangedCommand}" /> </i:EventTrigger> </i:Interaction.Triggers> </ListBox></code>
References 'i' namespace
To use EventTrigger and InvokeCommandAction, you need to reference the System.Windows.Interactivity assembly. Open the project's References panel and navigate to Add Reference > Assembly > Extension.
Bind command to ViewModel
In the ViewModel, create a public command to handle the event:
<code class="language-csharp">public ICommand SelectedItemChangedCommand { get; }</code>
Bind the command to the window’s DataContext:
<code class="language-csharp">this.DataContext = new MyAppViewModel();</code>
Handling SelectedItemChanged event
In MyAppViewModel, implement the SelectedItemChangedCommand and perform the necessary logic, such as getting and grouping tags, just like in the original event handler.
By following these steps, you have successfully moved the SelectionChanged event handling to the ViewModel, thus following MVVM principles and separating the UI logic from the data layer.
The above is the detailed content of How to Bind WPF UI Events (like SelectionChanged) to ViewModel Commands in MVVM?. For more information, please follow other related articles on the PHP Chinese website!