Can anyone explain why, when I step through my unit tests with the debugger, that I get null references whenlooking at objects or properties. For example:
1 [TestMethod] 2 [Description('Test to confirm that upon initial class creation, the login view is loaded as the default content for the TaskRegion.')] 3 public void Shell_Initialisation_LoginViewIsLoadedByDefault() 4 { 5 Shell shell = new Shell(); 6 7 TestPanel.Children.Add(shell); 8 9 Shell_ViewModel viewModel = shell.DataContext as Shell_ViewModel; 10 11 Assert.IsTrue(viewModel.TaskRegionContent is ContentControl); 12 13 EnqueueTestComplete(); 14 }
[Line 9] When I set my viewModel field to the DataContext of the shell view I get a ‘object not set to instance…’ exception. I know for sure that my datacontext is being set in my shell.xaml.cs; entire file:
1 using System.Windows; 2 3 namespace eg.WorkManager.UI.Shell 4 { 5 public partial class Shell 6 { 7 8 public Shell() 9 { 10 InitializeComponent(); 11 this.Loaded += new RoutedEventHandler(Shell_Loaded); 12 } 13 14 void Shell_Loaded(object sender, RoutedEventArgs e) 15 { 16 this.DataContext = new Shell_ViewModel(); 17 } 18 } 19 } 20
I know I’m doing something wrong, but can anyone explain what?
Thanks, Mark
I am guessing that the problem is that you are instantiating the Shell object in isolation. Have you confirmed that Shell_Loaded (the Loaded event) is even being called?
Why are you not creating your view model as a static resource in your xaml? With MVVM, I usually create it as a static resource in the xaml and then bind it as the data context in the LayoutRoot… all in xaml.