How can I notify child controls changes to a parent

What is the best way to update a child control for changes to the parent.

I have several child controls located inside my parent, and I can imagine two ways to send them change information.

1) connect the child control to the event in the parent element and fire this event when the parent changes

2) save the list of children in the array and iterate over the array when this happened, and call the method in the child to handle new changes.

I hope I describe it well.

Both work, but there is probably the right way to handle this and the wrong way.

EDIT: below is my code ... for an event method. I am not happy with the way I connected the child with the parent, and any suggestions.

Parent...

public class A_Parent { public delegate void DelUpdateMessage( string msg ); public event DelUpdateMessage UpdateMessage; public A_Parent() { a_Child1.prnt = this; a_Child2.prnt = this; a_Child3.prnt = this; a_Child4.prnt = this; } private void FireUpdateMessageEvent( string message) { var handlers = UpdateMessage; if (handlers != null) handlers( message ); } } 

Child...

 public class A_Child { A_Parent pnt; public A_Parent prnt { set { pnt = value; pnt.UpdateMessage += new A_Parent.DelUpdateMessage(pnt_UpdateMessage); } } void pnt_UpdateMessage(string msg) { } } 
+4
source share
3 answers

Your solution # 1 is the best bet, as it allows you to change your implementation without changing the parent. Since it may not matter to parents if they have children, an event-based approach is ideal.

UPDATE

The reverse event approach is insincere. People say that parents clearly know what interests them, and I just do not agree with this statement. My projects usually have children dynamically interested in parents, and children signing up for events are usually the most favorable way to do this.

You can find such examples in the .NET model, for example, on a page that has events that you can bind to.

+5
source

Events here are not suitable. The parent never has a problem figuring out which child controls should be notified. Just add a public method to UC like UpdateMessage (). The parent can directly call them.

Reserve events to be able to notify listeners when you have no idea which listeners might be interested. The presence of a "reverse event", as you contemplate, is unhealthy, it contains a link to the form. The form should never be mentioned so that it can receive garbage collection when it closes. This is not a problem because the link is maintained by the child control, but the principle holds.

+2
source

An event mechanism is a common procedure for such tasks. It will be much more flexible than your second solution.

0
source

Source: https://habr.com/ru/post/1307576/


All Articles