Subscribe to C# codes        RSS Feed
-----

Extension for dealing with associated controls within a host controls event

Icon Leave Comment
public static class UIExtensions
{

public static Control GetAssociatedControlByType(this Control sender, Type TypeOfDesiredControl)
{
// designed for dtCards
// Imagine this, you have two controls side by side on a form. When you do something in the left, you'd like to manipulate the right control as well.
// You hard code the names...
//
// yourControl_OnEvent(sender,e)
// {
// yourControl.Text = "this happens here";
// associatedControl.Text = "and this over there";
// }
//
// great... that works for now... but let's say you want to make 200 rows of controls just like this!
// Since you hard coded the control names, you have to write this function 200 times!
// fucken A right?
//
// But we can make our function abstract... first rewrite it to
//
// yourControl_OnEvent(sender,e)
// {
// ((TextBox)sender).Text = "this happens here";
// ... // fuck, how do I fix the associated control...
// }
//
// We can fix the first part easy, but the 'associated' control will be a bit more tricky.
// luckily, I solved this problem. Plus, I made it into an extension method, so you're really going to have a ball.
//
//
// yourControl_OnEvent(sender,e)
// {
// ((TextBox)sender).Text = "this happens here";
// TextBox theOtherControl = ((Control)sender).GetAssociatedControlByType(typeof(TextBox));
// theOtherControl.Text = "this happens here";
// }
//
// Excelent, right? Just put both controls within a Canvas, and this will signify that they are associated! Then this extension works.



// GetAssociatedControlByType
// search a parent's children for an associeted control of the specified type.
// A reference to this control is returned.
//
// this Control

Control srcControl = (Control)sender;
Type typeOfTheDesiredControl = TypeOfDesiredControl; // typeof(ComboBox);
// Desired property to set...
// Desired value to set...


UIElementCollection parentsChildren = ((Canvas)srcControl.Parent).Children;
foreach (Control ctrl in parentsChildren)
if (ctrl.GetType() == typeOfTheDesiredControl)
{
return ctrl;
}
return null;
}

}

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

September 2014

S M T W T F S
 123456
78910111213
1415161718 19 20
21222324252627
282930