Home > Backend Development > C++ > How to Bind WPF ListBox SelectionChanged Events to ViewModel Commands?

How to Bind WPF ListBox SelectionChanged Events to ViewModel Commands?

Linda Hamilton
Release: 2025-01-12 22:21:44
Original
170 people have browsed it

How to Bind WPF ListBox SelectionChanged Events to ViewModel Commands?

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.

Solution

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

Reference System.Windows.Interactivity

  • Add a reference to the assembly via Add Reference > Assembly > Extensions.
  • Use full namespace: xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity".

Additional Notes

    The
  • Command property is bound to the command defined in the ViewModel.
  • This pattern simplifies UI event handling and enhances separation of concerns.
  • Be sure to reference the 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!

source:php.cn
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