0
public class LDLTrackViewModel : RailwayViewModel { private LDLTrack _ldlTrack; public LDLTrack LDLTrack { get => _ldlTrack; set { _ldlTrack = value; OnPropertyChanged("LDLTrack"); } } public LDLTrackViewModel(LDLTrack ldlTrack) { LDLTrack = ldlTrack; LineCoords = new ObservableCollection<LineCoordinates>(ldlTrack.LineCoordList); ZIndex = -50; } 

}

My system is set up that I've filled my models with data through reading a big file. I then pass these models to various view models via their constructor (I have the same amount of view models as I do models):

LDLTracks = new ObservableCollection<LDLTrackViewModel>(TrainSimAllData.AllLDLTracks.Select(ldl => new LDLTrackViewModel(ldl))); 

Where LDLTracks is a collection of LDLTrackViewModels. I then bind to this list of view models in my view. I'm wondering if this is the normal way to go about things or whether there's a better approach?

2 Answers 2

3

Personally I would not have an issue with the view model constructor taking an LDLTrack and using it to populate itself. That's a fairly tidy, well-encapsulated way of doing things.

What I wouldn't be so keen on is then exposing that model to consumers via a property - instead, I'd populate fields explicitly defined for the properties that the view model represents:

public class LDLTrackViewModel : RailwayViewModel { private readonly string _theFoo; private readonly int _theBar; public string TheFoo => _theFoo; public int TheBar => _theBar; public LDLTrackViewModel(LDLTrack ldlTrack) { _theFoo = ldlTrack.Foo; _theBar = ldlTrack.Bar; } } 

This will help to reduce coupling - the view model's job is to communicate certain information and the constructor allows the LDLTrack model to be one source of that information, without further binding other consumers to that type.

1
  • That makes sense - I think I remember a tutorial doing a similar thing now I think about it as well. Thank you! Commented Jul 3, 2019 at 13:35
0

I think the constructor should be reserved for dependency injection. The data can be mapped in many ways. I do it like this for one of my MVVM apps

https://github.com/AndersMalmgren/FreePIE/blob/54830badaf876737b2b9c5bf2cd2c05e65ac0450/FreePIE.GUI/Views/Curves/CurveViewModel.cs#L32

Used like

 private void CreateCurvesModel() { Curves = new BindableCollection<CurveViewModel>(settingsManager.Settings.Curves.Select(c => curveModelFactory().Configure(c))); } 
1
  • I would go the same way. If you are using any DI mechanism, the constructor should be constructed automatically by this mechanism and all dependencies should be injected. Since the model is usually dynamic, it will not probably be injected but rather assigned. I usually have an "Initialize" method to set it up, to keep DI doing its job. Commented Nov 20, 2024 at 16:24

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.