WPF-FindName不应该返回null [英] WPF - FindName Returns null when it should not

查看:232
本文介绍了WPF-FindName不应该返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

FindName对我来说是坏的:(



我要寻找的对象在那里。我有证据。



这里是场景:

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

popup 为null,但并非总是如此。只是有时,但是即使将其设置为null,我要找的孩子也在那里。



我在它为空,并获取了这两个屏幕截图。



FindName为 popSelectIteration返回null的地方。





所以我想念的是什么?为什么FindName找不到它?如您从中看到的那样屏幕快照不是时间问题(FindName手表为空,但直接路径很好)。



有没有更好的方法来找到控件?

p>

侧面注释:在XAML中插入了有问题的切换按钮,可以在以下问题中找到它: WPF-FrameworkElement -枚举所有后裔吗?






更新:我做了一些挖掘了解为什么有时失败,有时又成功。我有一个动画,它调用 NameScope.SetNameScope((DependencyObject)form,new NameScope()); (完整的方法代码此处)。在那之后,FindName开始失败。



我真的不明白那个电话。我想我复制并粘贴了代码。无论如何,我将其注释掉。但是我很想知道为什么这会失败。

解决方案

我想这与视觉和逻辑之间的差异有关树。该控件在逻辑树中,但也许尚未应用此控件的模板,因此FindName不会返回任何有用的信息。



您可以尝试调用ApplyTemplate ();



这也可以解释为什么有时返回某些内容。


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.

解决方案

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.

这篇关于WPF-FindName不应该返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆