0

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

BigScary
  • 530
  • 1
  • 6
  • 19

1 Answers1

1

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 DataContext in your XAML, however that's not the same as setting the textGameClientModel property

You need to do something like this to set the property equal to your DataContext first

this.textGameClientModel = this.DataContext as GameClientModel;

or simply cast your DataContext as your class to setup the event

((GameClientModel)this.DataContext).runsPublished += textGameClientModel_runsPublished;

As a side note, I never recommend hardcoding the DataContext into a UserControl like you have. By doing so, you are preventing any other DataContext from getting passed to the UserControl, which kind of defeats one of the biggest advantages of WPF/MVVM, which is having separate UI and data layers.

Community
  • 1
  • 1
Rachel
  • 130,264
  • 66
  • 304
  • 490
  • Well I don't entirely get it, but it certainly works. Thanks very much! :) – BigScary Dec 17 '12 at 17:55
  • @BigScary The `DataContext` is the data layer that is behind your UI layer, which is usually referenced by the UI layer when you do a binding. I actually have a post on my blog that explains exactly what the `DataContext` is in simple terms. [What is this “DataContext” you speak of?](http://rachel53461.wordpress.com/tag/wpf-datacontext/) You may find useful if you're new to WPF :) – Rachel Dec 17 '12 at 17:57