views:

27

answers:

1

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

+1  A: 

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

Thomas Levesque
What Thomas is trying to say is that stuff that's declared in the UserControl.Resources is only accessible through the this.Resources["SomeResource"] indexer, The only reason you see the property xamlTestObj is because you gave it a x:Name, but xaml only loads elements that are within the content area (<Grid>) when InitializeComponents() in the constructor is called, Resources are not part of the Content area hence your behaviour
Neil