【发布时间】:2016-03-21 16:17:07
【问题描述】:
在我的后续第二行中,我发现了一个转换错误参数:
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
提前,感谢您的帮助。
【问题讨论】:
-
ReadData只返回一个值,而ObservableCollection的构造函数需要IEnumerable<T>。只需更改为使用集合初始化程序ListeStacks = new ObservableCollection<UserStackVM> { _listeStack };
标签: c# json mvvm converter observablecollection