r/csharp•
Dr-VanNostrand

WPF MVVM: How to refresh DataGridView on update of source data?

I am having a hard time trying to figure out how to trigger the CollectionChanged event to refresh a DataGridView control. I have a function in one view model that triggers a PropertyChanged event in all ViewModels to trigger a UI refresh, which works for all properties aside from ObservableCollections.

My base view model class:

abstract class BaseVM : INotifyPropertyChanged {
	private static List<BaseVM> _list = [];

	public static void Register(BaseVM viewModel) {
		var type = viewModel.GetType();

		for (int i = _list.Count - 1; i >= 0; i--) {
			if (_list[i].GetType() == type) {
				_list.RemoveAt(i);
			}
		}

		_list.Add(viewModel);
	}

	public static void NotifyAll() {
		foreach (var item in _list) {
			item.NotifyPropertyChanged();
		}
	}

	public event PropertyChangedEventHandler PropertyChanged;

	public void NotifyPropertyChanged(string propertyName = "") {
		PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
	}
}

The view model that I am trying to trigger a CollectionChanged update in:

class LoadingVM : BaseVM {
    public LoadingVM() {
        BaseVM.Register(this);
        LoadCases.CollectionChanged += NotifyCollectionChanged;
    }

    private readonly Loading _loading = Loading.Instance;

    public ObservableCollection<UltimateLoadCase> LoadCases {
        get => _loading.LoadCases;
        set {
            _loading.LoadCases = value;
            NotifyCollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }
    }
        
    public void NotifyCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
        switch (e.Action) {
            case NotifyCollectionChangedAction.Add:
            case NotifyCollectionChangedAction.Remove:
            case NotifyCollectionChangedAction.Reset:
                LoadCases = _loading.LoadCases;
                break;
        }
    }

    public string HeaderM2 => $"M2 (kN-m)";
    public string HeaderM3 => $"M3 (kN-m)";
    public string HeaderP  => $"P  (kN)";
    public string HeaderT  => $"T  (kN-m)";
    public string HeaderV2 => $"V2 (kN)";
    public string HeaderV3 => $"V3 (kN)";
}

And the function in a different view model that I am trying to have trigger a UI update in all view models:

public UnitSystem SelectedUnitSystem {
	get => _setup.SelectedUnitSystem;
	set {
		_setup.SelectedUnitSystem = value;
		BaseVM.NotifyAll();
	}
}

Posted Jul 6, 2025, 7:32 PM UTC

010
Loading comments…