Search code examples
c#wpfmvvm

Convert List<Model> to ObservableCollection<ViewModel>


I am considerably new to MVVM implementation. This might sound like a repetitive question but there is nothing that I could find that would help me understand better with my knowledge which is basic. I have a Model class with members as shown here:

public class Model
{
    public string Name { get; set; }
    public int Age { get; set; }
    public List<Model> Children { get; set; }
}

I have wrapped this model class in a view model but with ObservableCollection in place of List.

public class ViewModel
{
    private Model model;
    public ViewModel()
    {
        model = new Model();
    }
    //getters and setters for both Name and Age

    public ObservableCollection<ViewModel> Children
    {
        //how to convert List<Model> to ObservableCollection<ViewModel> here?
    }
}

I definitely do not want to expose my Model class to the view which is why I need to create an ObservableCollection of the VM class. Not sure how to achieve this though. Any help appreciated.


Solution

  • You are probably looking for the following:

    public class Model
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public List<Model> Children { get; set; }
    }
    public class ViewModel
    {
        public ViewModel(Model m)
        {
            Name = m.Name;
            Age = m.Age;
            Children = new ObservableCollection<ViewModel>(m.Children.Select(md=>new ViewModel(md)));
        }
    
        public string Name { get; set; }
        public int Age { get; set; }
        public ObservableCollection<ViewModel> Children { get; set; }
    
        public Model GetModel()
        {
            return new Model()
            {
                Age = Age,
                Name = Name,
                Children = Children.Select(vm=>vm.GetModel()).ToList(),
            };
        }
    }
    

    You will note that a lot of that is boilerplate code. But if you do it this way, your model/viewmodel are completely separated, which will save you SO many problems down the line.