Click here to Skip to main content
15,896,118 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hello,

can we access dynamically created controls globally.
for eg:
C#
class Dynamiccontrols
{
  void create()
{
label lbl=new label();
textbox txt=new textbox();
}
void access()
{
// can we access above label and text here.
// or in any other class
lbl.Content="Name"; // like this

}


if we create a control at Xaml(designtime) we can use it in through out the class.
How can we do that for controls crested from code.
Posted
Updated 29-Jul-11 1:56am
v2

Using your example, you should call RegisterName for every dynamically created control:

label lbl = new label();
lbl.Name = "ExampleLabel";

RegisterName("ExampleLabel", lbl);


You can then try to locate your control like this:

object j = this.FindName("ExampleLabel");

if (j.GetType() == typeof(Label))
{
   string s = ((Label)j).Name;
}


Enjoy
 
Share this answer
 
Comments
VK k 1-Aug-11 2:59am    
Thanku..
its working.
Sergey Alexandrovich Kryukov 2-Aug-11 4:00am    
Why register a name? Also, there is no such thing as a non-dynamic control.
--SA
UJimbo 2-Aug-11 9:46am    
I apologize for the late reply. Dynamic control might not be the correct way to describe a programmatically added control; I blame the fact English is not my native language.
As for calling RegisterName, my method to approach this question uses FindName to locate an object. During some fast testing, I could not discover such a created control without doing the above.
I find the VisualTreeHelper class[^] very useful to get children inside a parent control (dynamic or otherwise).
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 2-Aug-11 3:59am    
Useful class, but how is it relevant? Do I miss something? Also, there is no such thing as not dynamic control (please see my answer).
--SA
Just a note: In essence, there is no such thing as non-dynamic control. All control instances are created during run time, always. The fact that a control is declared in XAML does not change this. XAML is merely used as a data source for setting up a window. All controls are created and added during run time anyway. This is nothing which could be considered as "more dynamic" as that.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900