2011-03-01 76 views
1

什麼是從XML做視圖模型是最好的辦法:如何將數據LINQ嵌套到ObservableCollection中並嵌套ObservableCollection?

<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(); 

回答

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; 
} 
1

這應該是直截了當不夠的 - 只是做內部的選擇另一個嵌套LINQ查詢 - 然後你可以使用的ObservableCollection構造函數需要和IEnumerable。

爲了保持您的理智,您可能需要將其分解爲單獨的功能!

+0

加上最後評論! – KyloRen 2017-02-14 10:15:23