2015-09-14 61 views
0

我想将一些示例数据提供给ViewModel,它包含要在XAML中绑定的数据。下面是代码:无法创建类型'%0'的实例 - Windows Phone 8.1中的错误

private NotifyTaskCompletion<ObservableCollection<Auction>> _recentAuctions; 

    public NotifyTaskCompletion<ObservableCollection<Auction>> RecentAuctions 
    { 
     get 
     { 
      return _recentAuctions; 
     } 
     set 
     { 
      _recentAuctions = value; 
      NotifyPropertyChanged("RecentAuctions"); 
     } 
    } 

    public MainMenuViewModel() 
    { 
     RecentAuctions = new NotifyTaskCompletion<ObservableCollection<Auction>>(dataService.GetRecentAuctions()); 
    } 

(它使用NotifyTaskCompletionMDSN article模式)

GetRecentAuctions方法:

public async Task<ObservableCollection<Auction>> GetRecentAuctions() 
    { 
     return new ObservableCollection<Auction> 
     { 
      new Auction 
      { 
       Percentage = "69", 
       Title = "Szybsza spłata", 
       Date = "przed chwilą" 
      }, 
      new Auction 
      { 
       Percentage = "33", 
       Title = "Kolejna pożyczka, tym razem na remont.", 
       Date = "1 minutę temu" 
      } 
     }; 
    } 

到目前为止,它工作得很好 - 该项目显示在<ListView>。 的问题时,我想测试它是否能异步工作开始,要做到这一点我想补充这个“等待”线:

public async Task<ObservableCollection<Auction>> GetRecentAuctions() 
    { 
     await Task.Delay(TimeSpan.FromSeconds(1)); 
     return new ObservableCollection<Auction> 
     { 
      ... 

,我得到以下错误:

A first chance exception of type 'System.NullReferenceException' occurred in XXX.exe 'XXX.exe' (CoreCLR: .): Loaded 'C:\windows\system32\System.Runtime.WindowsRuntime.UI.Xaml.NI.DLL'. Cannot find or open the PDB file. A first chance exception of type 'Windows.UI.Xaml.Markup.XamlParseException' occurred in XXX.exe WinRT information: Cannot create instance of type '%0' [Line: 16 Position: 10]

谁能解释这种行为?缺什么?谢谢你的帮助。

回答

0

很难说,但它看起来像我试图在ViewModel的构造函数中异步加载数据,问题是VM将在数据加载之前完成创建。如果您引用的代码中的任何数据项预计将被初始化,您可以运行到System.NullReferenceException

我会建议如果要异步加载数据,不要在VM构造函数中执行。

您可以使用Behaviors SDK挂接页面的Loaded事件,然后调用到您的VM中。

相关问题