I’m trying the MVVM pattern and I’ve run into a problem.
Here’s how I instantiate my model:
<common:LayoutAwarePage
...
...(omitted boiler plate generated lines here)
...
...
mc:Ignorable="d">
<common:LayoutAwarePage.DataContext>
<local:TextGameClientModel x:Name="textGameClientModel"/>
</common:LayoutAwarePage.DataContext>
But when I try to use it, I get a NullReferenceException because this.textGameClientModel is NULL:
public MainPage()
{
this.InitializeComponent();
this.textGameClientModel.runsPublished += textGameClientModel_runsPublished;
}
I’ve also tried the same line in the Page’s OnNavigateTo handler, and also in the OnLoaded handler, but with the same result.
Where is the right place to hook up my event handler?
(Please don’t let my code-behind in an MVVM project distract you from the question. My use of a RichTextBox has forced me to color outside the lines a little.)
I actually wrote an answer about the WPF Creation Steps fairly recently, however that’s not the problem in this case.
In this case, you are setting the
DataContextin your XAML, however that’s not the same as setting thetextGameClientModelpropertyYou need to do something like this to set the property equal to your
DataContextfirstor simply cast your
DataContextas your class to setup the eventAs a side note, I never recommend hardcoding the
DataContextinto aUserControllike you have. By doing so, you are preventing any otherDataContextfrom getting passed to theUserControl, which kind of defeats one of the biggest advantages of WPF/MVVM, which is having separate UI and data layers.