1

从 xml 执行 ViewModel 的最佳方法是什么,例如:

<Cars>
 <Car>
   <Name/>
   <Model/>
   <Parts>
     <Part>
         <PartName/>
         <PartType/>
     </Part>
     <Part>
         <PartName/>
         <PartType/>
     </Part>
   </Parts>
 </Car>
</Cars>

会不会像

public class PartViewModel : INotifyPropertyChanged
{
    private string _PartName;
    private string _PartType;
    //... and proper get/seters for NotifyPropertyChanged
};

public class CarViewModel : INotifyPropertyChanged
{
    private string _Name;
    private string _Model;
    private ObservableCollection<PartViewModel> _parts;
    //... and proper get/seters for NotifyPropertyChanged
};

那么 LINQ 会如何填充 CarViewModel 呢?

 List<CarViewModel> FeedItems = (from carsXdoc in xdoc.Descendants("Cars")
                                 select new CarViewModel()
                                 {
                                     Name = carsXdoc.Element("Name").Value,
                                     Model = carsXdoc.Element("Model").Value,
// And then ? how do you fill nested observable collection with parts ?
                                 }).ToList();
4

2 回答 2

3

像下面这样的东西应该可以解决问题:

List<CarViewModel> FeedItems = (from carsXdoc in xdoc.Descendants("Cars")
                                select new CarViewModel()
                                {
                                    Name = carsXdoc.Element("Name").Value,
                                    Model = carsXdoc.Element("Model").Value,
                                    Parts = ToObservableCollection(from part in carsXdoc.Element("Parts").Descendants("Part")
                                                                   select new PartViewModel()
                                                                   {
                                                                       PartName = part.Element("PartName").Value,
                                                                       PartType = part.Element("PartType").Value,
                                                                   })
                                }).ToList();

ToObservableCollection()方法:

ObservableCollection<T> ToObservableCollection<T>(IEnumerable<T> sequence)
{
    ObservableCollection<T> collection = new ObservableCollection<T>();
    foreach (var item in sequence)
    {
        collection.Add(item);
    }

    return collection;
}
于 2011-03-01T20:28:07.147 回答
1

这应该足够直截了当——只需在 select 中执行另一个嵌套的 LINQ 查询——然后您可以使用采用和 IEnumerable 的 ObservableCollection 构造函数。

为了保持理智,您可能希望将其分解为一个单独的函数!

于 2011-03-01T20:18:48.890 回答