无法转换viewModel和ObservableCollection

时间:2016-03-21 16:17:08

标签: c# json mvvm converter observablecollection

在我的第二行中,我发现了一个转换错误参数:

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

我的错误是:

  

无法转换为&#39; MyStack.ViewModels.UserStackVM&#39;至   &#39; System.Collections.Generic.List&#39;

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

每次前进,谢谢你的帮助。

1 个答案:

答案 0 :(得分: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 } );