Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create instance of viewmodel in xaml

I've been searching for an answer to this but I can't seem to find one even though the question has been asked before. I have a viewmodel and I would like to add it to the application's resources in the xaml, but when I try it says "Cannot create an instance of 'AppViewModel'.

<Application.Resources>
   <src:AppViewModel x:Key="MainViewModel"/>
</Application.Resources>

I can add it to the resources in the code behind like this:

    CurrentViewModel = New AppViewModel
    Me.Resources.Add("MainViewModel", CurrentViewModel)

But that leaves me with squiggly lines in the xaml saying 'The resource "MainViewModel" cannot be resolved.'

Everything compiles fine and works without any issues - the bindings get bound and all that, but I would just like to get rid of the squiggly lines. I've read that you have to have a zero argument constructor on the viewmodel, but I have that and still have this error.

like image 779
Barry Franklin Avatar asked Oct 10 '22 14:10

Barry Franklin


1 Answers

I just figured out that there was a null reference happening when the view model was being initialized that wasn't happening when I initialized the view model in the code behind. Apparently the view model gets initialized at different times depending on how you add it to the resources. This seems odd to me, but it is fixed...

like image 67
Barry Franklin Avatar answered Oct 13 '22 09:10

Barry Franklin