引用在 xaml 中声明为静态资源的自定义 obj 为 null。为什么?
我有一个小型 Silverlight 3 测试应用程序。这是学习Silverlight、XAML、绑定等的练习。我有一个小测试类(Test),它具有三个属性; Val1、Val2 和总和。我已在 XAML 中声明了一个资源,如下所示:
<UserControl.Resources>
<app:Test x:Name="xamlTestObj"></app:Test>
</UserControl.Resources>
我在用户控件上有一个按钮。该按钮背后的代码如下所示:
xamlTestObj.Val1 += 100;
xamlTestObj.Val2 += 300;
解决方案构建成功,但是当我运行它时,在引用 xamlTestObj 时,我在按钮处理程序中收到 NullReferenceException。如果我将对象从用户控件的资源列表中拉出,我就能够成功执行按钮单击。就像:
Test xamlTestObj = (Test)Resources["xamlTestObj"];
xamlTestObj.Val1 += 100;
xamlTestObj.Val2 += 300;
让我困惑的是为什么我需要将对象从资源列表中取出。在我看来,如果编译器可以看到 xamlTestObj 引用,那么它应该在其声明的范围(在本例中为用户控件)的生命周期内“活动”。 WPF 控件的行为方式如下。也就是说,我可以访问放置在用户控件上的任何文本框和按钮。
谁能帮我解决这个问题吗?
谢谢 :-)
I have a small Silverlight 3 test application. This is an exercise in learning Silverlight, XAML, binding, etc. I have a small test class (Test), which has three properties; Val1, Val2, and Sum. I have declared a resource in the XAML as follows:
<UserControl.Resources>
<app:Test x:Name="xamlTestObj"></app:Test>
</UserControl.Resources>
I have a button on the user control. The code behind for this button looks like:
xamlTestObj.Val1 += 100;
xamlTestObj.Val2 += 300;
The solution builds successfully, but when I run it I get a NullReferenceException in the button handler when referencing xamlTestObj. I was able to execute the button click successfully if I pulled the object out of the user control's resources list. Like:
Test xamlTestObj = (Test)Resources["xamlTestObj"];
xamlTestObj.Val1 += 100;
xamlTestObj.Val2 += 300;
What confuses me is why I need to pull the object out of the resources list. It seems to me that if the compiler can see the xamlTestObj reference that it should be "live" for the lifetime of the scope it's declared in (in this case, the user control). The WPF controls behave this way. That is, I can access any of the text boxes and buttons I have placed on the user control.
Can anyone clear this up for me?
Thanks :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,只有可视化树中的元素会加载到
InitializeComponents
方法中相应的字段中。资源不是可视化树的一部分,它们仅在需要时加载,因此它们对应的字段保持为空。顺便说一句,您应该使用
x:Key
而不是x:Name
作为资源As far as I know, only elements in the visual tree are loaded into their corresponding fields in the
InitializeComponents
method. Resources are not part of the visual tree, they are only loaded when required, so their corresponding fields remain null.By the way, you should use
x:Key
rather thanx:Name
for resources