Access functions from user control without events?

Posted by BornToCode on Programmers See other posts from Programmers or by BornToCode
Published on 2012-10-22T13:37:27Z Indexed on 2012/10/22 23:17 UTC
Read the original article Hit count: 252

I have an application made with usercontrols and a function on main form that removes the previous user controls and shows the desired usercontrol centered and tweaked:

public void DisplayControl(UserControl uControl)

I find it much easier to make this function static or access this function by reference from the user control, like this:

MainForm mainform_functions = (MainForm)Parent; mainform_functions.DisplayControl(uc_a);

You probably think it's a sin to access a function in mainform, from the usercontrol, however, raising an event seems much more complex in such case - I'll give a simple example - let's say I raise an event from usercontrol_A to show usercontrol_B on mainform, so I write this:

    uc_a.show_uc_b+= (s,e) =>
 {
 usercontrol_B uc_b = new usercontrol_B();   DisplayControl(uc_b);
 };

Now what if I want usercontrol_B to also have an event to show usercontrol_C? now it would look like this:

uc_a.show_uc_b+= (s,e) => 
{
usercontrol_B uc_b = new usercontrol_B();   DisplayControl(uc_b);
uc_b.show_uc_c += (s2,e2) => {usercontrol_C uc_c = new usercontrol_C(); DisplayControl(uc_c);}
};

THIS LOOKS AWFUL!

The code is much simpler and readable when you actually access the function from the usercontrol itself, therefore I came to the conclusion that in such case it's not so terrible if I break the rules and not use events for such general function, I also think that a readable usercontrol that you need to make small adjustments for another app is preferable than a 100% 'generic' one which makes my code look like a pile of mud.

What is your opinion? Am I mistaken?

© Programmers or respective owner

Related posts about design-patterns

Related posts about observer-pattern