Access functions from user control without events?
- by BornToCode
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?