views:

414

answers:

4

I have 2 types of objects, Parents, and Children. I have an abstract class for these two objects. There are 2 types of parents, ParentA, ParentB and there are 2 types of children, ChildA, ChildB. These all inherited their corresponding base classes, i.e ParentA:Parent, ParentB:Parent, ChildA:Child, ChildB:Child.

Each parent has a collection of children. Type A Parents can only have Type A children, and Type B parents can only have TypeB children.

To add a child to a parent, I use the method addChild(child) defined in Parent abstract class. This method executes exactly the same for both parent types. In this method, I would like the parent to subcsribe tothe child's events. I use the following code:

internal void addChild(Child child)
{
 //Code I execute to add the child

 rChild.ChildPropertyChanged += ChildPropertyChanged;
}

Now, when I execute the following code:

ParentA parentA = new ParentA();
ChildA childA = new ChildA();

parentA.addChild(childA);

and follow the event in the childA object, I see that after the subcsription code above, the event is still null. Why is this event still null?

+1  A: 

Lacking any further code, the only issue I can see with that you may not attaching the event to the correct object. Maybe something like this would fix it:

internal void addChild(Child child)
{        
    //Code I execute to add the child        
    child.ChildPropertyChanged += ChildPropertyChanged;
}
CAbbott
A: 

It maybe because that no other objects subscribed to the client event.

In this case the client event is null and therefor the parent event.

Try this:

var childA = new ChildA();
var parentA = new ParentA();

childA .PropertyChanged = new ChildAPropertyChangedEventHandler(PropertyChangedMethod);
parentA.AddChild(childA );
Mohammadreza
A: 

The code example is not really that complete, so it is difficult to guess what the problem id.

But could it be that you have created a new event definition in the ChildA class that hides the original event definition in the Child class?

Pete
+2  A: 

Thanks everyone, but everything works correctly now. I feel stupid for it, but somehow it eluded me all day yesterday. Indeed, the prolem is the line:

child.ChildPropertyChanged += ChildPropertyChanged;

where ChildPropertyChanged was the event and NOT the method. The correct way, obviously, is something like

child.ChildPropertyChanged += OnChildPropertyChanged;

where OnChildPropertyChanged is a method.

I'm converting my code over from VB, where I'm used to a single line to raise an event :)

sbenderli
Just a comment on your naming convention. You are creating a function OnXYZ. Normally, in the .NET framework, when there exists an OnXYZ function, it is related to an XYZ event that the class itself raises. It is normally not an event handler for an event that it receives from a referenced object. So using this name for the event handler may be confusing.
Pete