Question

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 ?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top