Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - FindName Returns null when it should not

Tags:

c#

wpf

findname

FindName is broken for me :(

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".

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

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: 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.

like image 380
Vaccano Avatar asked Feb 18 '10 00:02

Vaccano


2 Answers

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.

like image 141
Patrick Klug Avatar answered Sep 23 '22 06:09

Patrick Klug


Try

LogicalTreeHelper.FindLogicalNode(button, "popSelectIteration"); 
like image 24
Shrike Avatar answered Sep 24 '22 06:09

Shrike