Referencing a custom obj, declared as a static res in xaml, is null. Why?
-
20-09-2019 - |
Question
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 :-)
Solution
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 than x:Name
for resources