WPF的InitializeComponent过程中获取控制空引用 [英] WPF Getting Control null reference during InitializeComponent

查看:753
本文介绍了WPF的InitializeComponent过程中获取控制空引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在窗口的构造我的InitializeComponent方法调用是通过XML运行,并添加控件,并将其插入到他们的活动。

So my InitializeComponent method call in the Window's constructor is running through the XML and adding the controls and plugging them into their events.

所以,当其中一个控件的属性更改它调用订阅了事件的方法。该方法引用了尚未建立控制。

So when a property of one of the controls changes it calls the Method that subscribes to the event. The method references a control that has not yet been built.

为什么会发生这种情况在这里这个命令?它曾在的WinForms,因为事件被不触发,直到后来,所有的对照创建之后。有没有办法迫使这在WPF?

Why does this happen in this order here? It worked in WinForms because the events were not fired until later, after all the controls were created. Is there a way to force this in WPF?

其他的解决方案,我看到的是

The other solutions I see are


  • 我要订阅初始化后的事件。这是一个deriere痛苦。

  • I need to subscribe to the events after initialization. This is a pain in the deriere.

我需要检查空每当我处理与控制。在deriere也痛,增加的是痛苦跑马圈地。

I need to check for null whenever i deal with a control. Also a pain in the deriere, with the addition of being pain-staking.

任何帮助吗?

推荐答案

我只是有这个问题太,并通过包装线在访问一个空检查空控制解决它。这似乎是一个黑客位变通办法的。

I just had this issue too, and solved it by wrapping the line accessing the null control in a null check. This seems like a bit of a hack workaround.

我觉得WPF正试图通过在InitializeComponent()中调用我们经过的事件是有帮助的这里,在努力确保任何UI逻辑(例如显示/隐藏相关部件)是基于复选框的初始状态执行。我测试有默认取消选中的复选框,事件处理程序不被调用,即使我已经其连接到这两个选中和未选中的事件。我甚至在屏幕上的一个复选框的空白WPF项目复制这一点,它的行为是一样的。

I think WPF is trying to be helpful here by calling our Checked event during InitializeComponent(), in an effort to ensure that any UI logic (e.g. showing/hiding related components) is executed based on the initial state of the checkbox. I tested having the Checkbox unchecked by default, and the event handler is not called, even though I have it wired to both the Checked and Unchecked events. I even reproduced this in a blank WPF project with a single Checkbox on the screen, and it behaves the same.

这个默认行为问题显然是一些其他组件尚未初始化。我觉得应该WPF等到所有的组件默认烧成经过事件之前初始化。这可能不会被认为是一个错误,但我一张纸条要添加到相关MSDN页面反正...

The problem with this default behavior is obviously that some of the other components are not yet initialized. I think WPF should wait until all the components are initialized before firing the Checked event by default. This might not be considered a bug, but I'm gonna add a note to the relevant MSDN page anyway...

这篇关于WPF的InitializeComponent过程中获取控制空引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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