0

I'm binding a DataGrid to an ObservableCollection<MyModel>. The grid consists of some columns that are bound to properties of the model via <DataGridTextColumn Content="{Binding LastName}" /> etc., which works fine.

Now I want to add a column SumOfAllReferencesToMyModelInstance to the grid with a calculated value, which takes the Id property of each MyModel in the collection and uses it to count the instance's occurrences in some other places, resulting in different values for each instance / grid row. I can easily bind the column to a custom property in my view model, but I fail to get a reference to the currently evaluated MyModel instance to read its Id, which apparently I need for the calculation. How can I achieve this?

I'd like to avoid adding a SumOfAllReferencesToMe property to the model class containing the calculated value since the calculation is not a part of the model.

I'm using MVVM with Caliburn.Micro, but I think that's irrelevant since this seems to be a more general issue to me.

Hannes
  • 273
  • 3
  • 14

1 Answers1

1

I'd like to avoid adding a SumOfAllReferencesToMe property to the model class containing the calculated value since the calculation is not a part of the model.

So replace MyModel with a view model that contains the values that you indend to display in the view. Binding directly to entity or business objects is rarely a good idea.

The MVVM way to solve this would be to wrap MyModel in a view friendly class, add another property to it and set and update it from the current "main" view model.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • I see, so in MVVM you would generally add a viewmodel class for each model class, which then provides both the model's properties and other stuff if needed. That makes sense. Is it common practice to directly attach the model's properties to the view model class (like ```public string LastName { get { return _model.LastName; } set { _model.LastName = value; } }```? – Hannes Aug 19 '21 at 15:57