Bind UI events to commands in WPF ViewModel
Following the MVVM architecture, moving UI events to ViewModel is more conducive to code maintenance and expansion. This article will focus on how to transfer the ListBox's SelectionChanged event from the code-behind file to the ViewModel, and use the provided code snippet as an example.
To do this, we need to use EventTrigger
together with InvokeCommandAction
(in the System.Windows.Interactivity
namespace):
<code class="language-xml"><ListBox ...> <i:Interaction.Triggers> <i:EventTrigger EventName="SelectionChanged"> <i:InvokeCommandAction Command="{Binding SelectedItemChangedCommand}" /> </i:EventTrigger> </i:Interaction.Triggers> </ListBox></code>
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
. Command
property is bound to the command defined in the ViewModel. System.Windows.Interactivity
namespace as directed to ensure successful implementation. The above is the detailed content of How to Bind WPF ListBox SelectionChanged Events to ViewModel Commands?. For more information, please follow other related articles on the PHP Chinese website!