Ayda Sayed
Ayda Sayed

Reputation: 509

MVVM: how to create a ViewModel from Model object

I want to get values of my model and create a viewmode

In my Model I have

   public class TestElement
    {
     public TestElement CurrentNode { get; set; }
    public TestElement Parent { get; set; }
    }

I have some method that do this

    if (thisNode == null)
            {
                thisNode = new TestElement { Name = name, Parent = CurrentNode };
                currentCollection.Add(thisNode);
            }

In my view model I want to create TestElementViewModel Parent and get my model Parent values

     public class TestElementViewModel
    {

    public TestElementViewModel Parent { get; set; }

I want to use it in this method

      public IEnumerable<TestElementViewModel> ToTreeViewModel(IEnumerable<TestElement> treemodel)
    {
        foreach (TestElementitem in treemodel)
            yield return new  TestElementViewModel
                {
                    Id = item.Id, 
                    Name = item.Name, 
                    Children = ToTreeViewModel(item.Children).ToList(), 
                  Parent = item.Parent
                };
      }

         }

How can I achieve that?

Upvotes: 1

Views: 1290

Answers (1)

failedprogramming
failedprogramming

Reputation: 2522

I'm guessing your casting error occurs on the the line

Parent = item.Parent

Well the Parent property in your TestElementViewModel isn't a TestElement type so you can't do that.

Try assigning a new TestElementViewModel instead.

Parent = new TestElementViewModel { Id = item.Parent.Id, Name = item.Parent.Name, ... }

One improvement you might want to consider is using wrappers in your ViewModel class, which will make assigning properties a little easier.

For example,

public class TestElementViewModel : INotifyPropertyChanged
{
    public TestElementViewModel(TestElement model)
    {
        Model = model;
        if(Model.Parent != null)
            Parent = new TestElementViewModel(Model.Parent);
    }

    public TestElement Model { get; private set; }

    private TestElementViewModel _parent;

    public TestElementViewModel Parent 
    { get { return _parent; }
      set { _parent = value; OnPropertyChanged("Parent"); }
    }

    public int Id
    {
        get { return Model.Id; }
        set { Model.Id = value; OnPropertyChanged("Id"); }
    }

    // rest of the properties need wrapping too
}

makes it so that you don't have to manually assign the properties each time you instantiate a new viewmodel.

Upvotes: 1

Related Questions