tags:

views:

622

answers:

2

FindName is broken for me :(

If you are an expert in such things I would love some help.

The object I am looking for is there. I have proof.

Here is the scenario:

ToggleButton button = (ToggleButton)sender;
Popup popup = (Popup)button.FindName("popSelectIteration");

popup is null but not always. Just sometimes. But even when it is set to null the child I am looking for is there.

I put a break point in when it was null and grabbed these two screenshots.

The is where FindName is returning null for "popSelectIteration":

alt text

But if you dig into the watch, you see that the child is there:

alt text

So what am I missing? Why does FindName not find it? As you can see from the screen shot this is not a timing issue (the FindName watch is null but the direct path is fine).

Is there a better way to find a control?

Side Note: If you are intersted in the XAML for the toggle button in question it can be found in this question: http://stackoverflow.com/questions/2285196/wpf-frameworkelement-enumerate-all-decendents.


Update: I did some digging to see why this fails some times and other times it works. I have an animation that calls NameScope.SetNameScope((DependencyObject)form, new NameScope()); (Full method code here). Right after that call the FindName starts to fail.

I don't really understand that call. I think I copied and pasted the code. Anyway, I commented it out. But I would love know why this is failing.

+1  A: 

I would guess it has to do with the difference between the visual and logical tree. The control is in the logical tree but maybe the template for this control has not been applied yet and therefore FindName won't return anything useful.

You could try to call ApplyTemplate(); on the container first.

This would also explain why it returns something sometimes.

Patrick Klug
+1  A: 

I would suggest to avoid using FindName function, based on my experience, expecially problematic when you try to find something in the DataTemplate applied to some control. Instead , if it possible (based on your software architecture) declare Popup in XAML and refer to it like resource or use Binding to set some Model property to it's reference. Good luck.

Tigran