【问题标题】:cannot convert viewModel and ObservableCollection无法转换 viewModel 和 ObservableCollection
【发布时间】: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&lt;T&gt;。只需更改为使用集合初始化程序ListeStacks = new ObservableCollection&lt;UserStackVM&gt; { _listeStack };

标签: c# json mvvm converter observablecollection


【解决方案1】:

'MyStack.ViewModels.UserStackVM' 到 'System.Collections.Generic.List'

ObservableCollection(T) Constructor 需要 List&lt;T&gt;(实例列表);您只提供一个实例。改成

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

ListeStacks.Add( _listeStack );

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 2021-12-10
    • 2011-07-05
    相关资源
    最近更新 更多