任何人都可以解释为什么当我通过调试器单步执行单元测试时,我在查看对象或属性时会得到空引用。 例如:
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 }[第9行]当我将viewModel字段设置为shell视图的DataContext时,我得到一个“未设置为实例的对象...”异常。 我确信我的datacontext是在我的shell.xaml.cs中设置的; 整个档案:
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我知道我做错了什么,但任何人都可以解释一下吗?
谢谢,马克
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 } 20I know I'm doing something wrong, but can anyone explain what?
Thanks, Mark
最满意答案
我猜测问题是您正在单独实例化Shell对象。 你确认Shell_Loaded(Loaded事件)甚至被调用了吗?
为什么不在xaml中将视图模型创建为静态资源? 使用MVVM,我通常在xaml中将其创建为静态资源,然后将其作为LayoutRoot中的数据上下文绑定...全部在xaml中。
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.
更多推荐
发布评论