Can't find dynamically generated control, using FindName() in WPF

5k Views Asked by At

I need to dynamically generate as much labels as I want, and access every single one of them when desired. but FindName() haven't been working...

Here's a simple example of what I do

I have a custom-written class, inherited from Label class, called myLabel. I've put a button on my WPF project. By clicking on it, an instance of myLabel class will dynamically be created and added to the grid (myGrid) like so :

myLabel LBL = new myLabel();
LBL.Height = 30;
LBL.Name = "MyLabel1";
LBL.Content = "I am a label.";
myGrid.Children.Add(LBL);

There's another button called "Change color" which should find the previously created Label and change it's foreground color. here's the code inside that button's click event:

Label Thelabel = (Label)myGrid.FindName("MyLabel1");
Thelabel.Foreground = Brushes.Azure;

The problem is that FindName() never finds anything and is always null ! How can I fix that problem ?

2

There are 2 best solutions below

2
On BEST ANSWER

There may be issues with name scoping that are causing the 'FindName' to return null.

An explanation of a different method for finding a particular named element, starting from a parent/ancestor can be found at this post: How can I find WPF controls by name or type?

give that a try and see if it works for you.

0
On

Actually, the root cause of not being able to find the dynamic control is because the control was not being registered first.

See: https://learn.microsoft.com/en-us/dotnet/api/system.windows.frameworkelement.registername

Assuming a custom user control named Hello

Hello myHello = new Hello();
myHello.Visibility = Visibility.Visible;
myHello.Name = "HelloWorld";
RegisterName("HelloWorld", myHello);

someGrid.Children.Add(myHello);

With RegisterName, you will be able to find the dynamically generated element.