I am having problems finding an named object declared in XAML in my codebehind file.
I want to initalize a ViewModel from inside my View. However I also need a reference to the ViewModel in my code behind file (basically for navigation support, handling events, etc. that I cannot do easily from my ViewModel)
<navigation:Page.DataContext>
<vm:JobsViewModel x:Name="ViewModel" />
</navigation:Page.DataContext>
However I get a null reference exception when I'm trying to access the ViewModel in my code behind:
Protected Overrides Sub OnNavigatedTo(ByVal e As System.Windows.Navigation.NavigationEventArgs)
MyBase.OnNavigatedTo(e)
ViewModel.Initalize() '<-- Exception here
End Sub
Some more research shows that the FindName
call for "ViewModel" in InitalizeComponent
returns null. I tried reading up on XAML namescopes etc. but as far as I see, this should be a simple case and just work, no?
Any pointers as to why this fails would be greatly appreciated. Thanks!
That's because your JobsViewModel
is not part of the visual tree, so FindName
doesn't find it. You can retrieve it through the DataContext
property instead.