<Window x:Class="ListViewSelectionChangedCommandNotFired.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ListViewSelectionChangedCommandNotFired"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
d:DataContext="{d:DesignInstance Type=local:MainWindow,
IsDesignTimeCreatable=True}"
DataContext="{Binding Mode=OneWay, RelativeSource={RelativeSource Self}}"
FontSize="16"
Loaded="Window_Loaded"
mc:Ignorable="d">
<UniformGrid Rows="1">
<ListView ItemsSource="{Binding DataList}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
SelectionChanged="ListView_SelectionChanged">
<b:Interaction.Triggers>
<b:EventTrigger EventName="SelectionChanged">
<b:InvokeCommandAction Command="{Binding SelectionChangedCommand}" />
</b:EventTrigger>
</b:Interaction.Triggers>
</ListView>
<TextBox x:Name="Output" />
</UniformGrid>
</Window>
using System.Collections.ObjectModel;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace ListViewSelectionChangedCommandNotFired;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
[INotifyPropertyChanged]
public partial class MainWindow : Window
{
[ObservableProperty]
private string? _selectedItem;
public MainWindow()
{
InitializeComponent();
}
public ObservableCollection<string> DataList { get; private set; } = new();
private void ListView_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
Output.Text += "SelectionChanged Event fired!\n";
}
[RelayCommand]
private void SelectionChanged()
{
Output.Text += "SelectionChanged Command fired!\n";
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DataList.Add("Sample data 1");
SelectedItem = DataList[^1];
DataList.Add("Sample data 2");
SelectedItem = DataList[^1];
DataList.Add("Sample data 3");
SelectedItem = DataList[^1];
}
}
Mini demo:
Win11 + .NET 7.0
CommunityToolkit.Mvvm Version="8.2.0"Microsoft.Xaml.Behaviors.Wpf Version="1.1.39"