2016-03-21 20 views
2

在我跟隨第二行中,我發現了一個轉換錯誤的說法:不能轉換視圖模型和的ObservableCollection

UserStackVM _listeStack = JsonWorker.ReadData(); 
ListeStacks = new ObservableCollection<UserStackVM>(_listeStack); // here 

我的錯誤是:

無法從「MyStack.ViewModels.UserStackVM」轉換爲 'System.Collections.Generic.List'

UserStackVM是一個ViewModel:

#region Properties 
     private string name; 
     ... 
     private string[] path; 
     ... 
     #endregion 

JsonWorker是使用Json.NET(http://www.newtonsoft.com/json)一個靜態類:

#region Properties 
     private static string _json; 
     private static UserStackVM _userStack; 
     #endregion  

     #region Methods 

     /// <summary> 
     /// Open the json config file. Create it if he doesn't exist. 
     /// </summary> 
     private static void OpenFile() 
     { 
      using (var stream = new FileStream(@"config.json", FileMode.OpenOrCreate)) 
      { 
       using (var reader = new StreamReader(stream)) 
       { 
        _json = reader.ReadToEnd(); 
       } 
      } 
     } 

     /// <summary> 
     /// Read the json config file and return all data. 
     /// </summary> 
     /// <returns></returns> 
     public static UserStackVM ReadData() 
     { 
      OpenFile(); 
      _userStack = JsonConvert.DeserializeObject<UserStackVM>(_json); 
      return _userStack; 
     }  
     #endregion 

每前進,感謝您的幫助。

+3

'ReadData'僅返回其中作爲構造爲'ObservableCollection'需要'的IEnumerable '的單個值。只需更改爲使用集合初始化器'ListeStacks = new ObservableCollection {_listeStack};' –

回答

2

'MyStack.ViewModels。 UserStackVM'至'System.Collections.Generic.List'

ObservableCollection(T) Constructor期望一個List<T>(實例的列表);你只提供一個實例。它更改爲

UserStackVM _listeStack = JsonWorker.ReadData(); 
ListeStacks = new ObservableCollection<UserStackVM>(); 

ListeStacks.Add(_listeStack); 

ListeStacks = new ObservableCollection<UserStackVM> 
             (new List<UserStackVM>() { listeStack }); 
+0

成功,謝謝! –

相關問題