views:

342

answers:

1

Hi.

I have a question regarding the MVVM design for C#/WPF. I've had a look at several demo applications, but they didn't really handle my problem. My application consists of objects that contain other objects. Much like in a parent - children relationship.

My question now is:

  • does the children attribute have to be a ViewModel
  • and if so, how do I create new Parent objects, which contain the existing Child objects via ViewModels?

I have sth like the following scenario:

            class Child{
            string Name;
            }

            class ChildVM{
            Child _child;
            string Name{return _child.Name;}
            }

            class Parent{
            string Name;
            List<Child> children;
            }

            class ParentVM{
            Parent _parent;

            string Name{return _parent.Name;}
            List<ChildVM> children {get;set;}

            ParentVM(Parent p){_parent = p;}
            }

    void CreateANewParent(){
                  List<ChildVM> children = new List<ChildVM>(){new ChildVM(new Child()),...};
                  ParentVM parent = new ParentVM(new Parent());
                  foreach(ChildVM child in children)
                  parent.children.Add(child);
               }

The problem here is, that the ParentVM contains the ChildVM, BUT the actual Parent (which is inside of the ParentVM) does not have the Child objects contained by the ChildVM objects. I also don't think it's a good idea to duplicate the Child objects, as it leads to redundance and in my application context there is also no need/possibility to create new Child objects.

I also thought about the following class design:

class ParentVM{
Parent _parent;

string Name{return _parent.Name;}
List<Child> children {get{return _parent.Children;}}
}

However, this would mean I would directly operate on the Model if I want to manipulate a ParentVM's Child object.

On the other hand I could simply leave the (Model) Parent blank and use the ParentVM to create a new Parent in the database. But is this a good way of handling the problem?

+1  A: 

Alright, I got some help and advice from a .NET forum: I'll solve the problem by providing a Get-Method for the Model inside of the ViewModel. So if I create a new Parent with existing ChildVMs, I just return the Child reference inside the ChildVMs and assign them to my new Parent.

Torsten