I am trying to “hook up” my viewmodel as a DataContext to my View. I am going with an application-wide one view-to-viewmodel scenario.
I like the idea of using the following method to attach (which it does successfully):
<UserControl ......Window Stuff.......>
<UserControl.DataContext >
<vm:MyViewModel/>
</UserControl.DataContext>
</UserControl>
However the xaml editor places a purple squiggly line under <vm:MyViewModel/> and hovertext gives error
"Cannot create instance of vm:MyViewModel"
But it correctly builds/runs my application and presents the data, which the method:
<UserControl>
<UserControl.Resources>
<DataTemplate DataType="{x:Type vm:MyViewModel}">
<vw:MyView/>
</DataTemplate>
</UserControl.Resources>
</UserControl>
Does NOT present my data, although it appears to be acceptable code.
Commenting-out the DataContext reference is really a pain just for making edits to the controls manually. Am I doing something incorrectly/am I forgetting something?
Thanks in advance! 🙂
There is likely something going on in the constructor of your view model that is preventing the model from being instantiated within Visual Studio.
Try adding a
returnstatement before anything is done in the view model’s constructor, rebuild and see if the error goes away.Here’s an extension method that will determine if the the current process is within visual studio:
And then in your constructor: