using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows; using System.Windows.Controls; using System.Windows.Data; namespace WpfApp028 { public class ViewModel: INotifyPropertyChanged { public ViewModel() { for (int i = 1; i < 10; i++) col.Add(new Data() { ID = i, Name = $"Row {i}" }); cvs.Source = col; } private ObservableCollection col = new ObservableCollection(); private CollectionViewSource cvs = new CollectionViewSource(); public ICollectionView View { get => cvs.View; } private int _rowCount; public int RowCount { get => this._rowCount; set { this._rowCount = value; OnPropertyChanged(); } } #region attached property public static readonly DependencyProperty AttPropProperty = DependencyProperty.RegisterAttached("AttProp", typeof(bool), typeof(ViewModel), new PropertyMetadata(false, OnPropChanged)); public static bool GetAttProp(DependencyObject obj) => (bool)obj.GetValue(AttPropProperty); public static void SetAttProp(DependencyObject obj, bool par) => obj.SetValue(AttPropProperty, par); private static void OnPropChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { DataGrid dg = d as DataGrid; if (dg == null) return; dg.SelectionChanged += (s, mbe) => ((ViewModel)(dg.DataContext)).RowCount = (int)(dg.SelectedItems).Count; } #endregion public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName)); } public class Data { public int ID { get; set; } public string Name { get; set; } } }