Reputation: 3804
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?
Upvotes: 1
Views: 1570
Reputation: 3804
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 :)
Upvotes: 2
Reputation: 12593
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?
Upvotes: 0
Reputation: 6968
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 );
Upvotes: 0
Reputation: 8098
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;
}
Upvotes: 1