Children.Add() and RegisterName()

484 views Asked by At

Currently pulling out ma hair over the following problem. My code adds Rectangles to a Grid as follows:

Dim rect As Rectangle
' Set a bunch of properties of rect here'

myGrid.Children.Add(rect)

It used to work beautifully, until I needed to find my rectangles in the grid. I've just spent an hour trying to figure out how exactly to use RegisterName(), but alas I'm failing at it.

Should it be myGrid.RegisterName(rect.Name, rect), rect.RegisterName(rect.Name, myGrid), or whatever else?

Should I do it before, after or instead of myGrid.Children.Add(rect). I've tried every single combination and the rectangles just don't show up on the grid any more.

2

There are 2 answers

0
Phonon On BEST ANSWER

Since no answers on here helped me, I'll post my own (semi-) solution. I I've read on multiple sites and forums, it's generally not a good practice to use FindName in this manner. It's really for parsing the existing XAML code, everything else is borderline hacking the method.

Things like VisualtreeHelper and certain other tricks can help get to the correct elements of GUI. One can always iterate through all available elements if there are not too many and performance is not a huge issue (it is in my case). I did it by simply creating an array of references to all the relevant UI elements and found them that way. Your solution might be different depending on implementation and design. My solution is not perfect and elegant, but it does the job with nearly no performance compromises.

1
Thomas Levesque On

I don't think you need to call RegisterName explicitly... Rectangle has a Name property, like all FrameworkElements, so you can just call FindName on the parent to find your Rectangle...