Richard S.
Richard S.

Reputation: 743

How to get/update property of parent object from child object

I have a class called Invoice

public Invoice() {
        this.ServiceId = 0;
        this.Sections = new List<Section>();            
    }

I have another class called Sections

public Section() {
        this.Items = new List<Item>();
    }

and yet another class called Item

public Item() {
        blah, blah;
    }

Now I am passing an object of Item into my windows user control, and I have the need to update the 'ServiceId' property located on my Invoice class. My question is there a way to edit that property from my item object? and how would I go about doing that.

Other information of note is that none of my classes inherit from anything. Meaning that Item does not inherit from Section and Section not from Inspection. They are simply list collections. Thanks for your help.

Upvotes: 0

Views: 1250

Answers (1)

jwatts1980
jwatts1980

Reputation: 7356

A good way to do this is through a hierarchical dependency injection. The Section class should have a constructor that requires an Invoice and a Parent or ParentInvoice property:

public Section() 
{
    this.Items = new List<Item>();

    public Invoice Parent { get; set; }

    public Section(Invoice parent) 
    {
        this.Parent = parent;
    }
}

And likewise with the Item; it should require a Section as a parent. Then from any item you will be able to use

Invoice i = this.Parent.Parent;

You can create methods that will add the sections and items like so:

public Invoice()
{
    //....
    public Section AddSection()
    {
        var s = new Section(this);
        Sections.Add(s);
        return s;
    }
    //...
}

Upvotes: 1

Related Questions