如何使用嵌套的 ObservableCollection 将 LINQ 数据连接到 ObservableCollection 中?
从 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();
What would be the best way to do ViewModel from an xml like:
<Cars>
<Car>
<Name/>
<Model/>
<Parts>
<Part>
<PartName/>
<PartType/>
</Part>
<Part>
<PartName/>
<PartType/>
</Part>
</Parts>
</Car>
</Cars>
would it be like
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
};
then how would LINQ look like to fill 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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像下面这样的东西应该可以解决问题:
ToObservableCollection()
方法:Something like following should do the trick:
ToObservableCollection()
method:这应该足够简单 - 只需在 select 中执行另一个嵌套 LINQ 查询即可 - 然后您可以使用采用 IEnumerable 的 ObservableCollection 构造函数。
为了保持理智,您可能需要将其分解为一个单独的函数!
This should be straight-forward enough - just do another nested LINQ query inside the select - you can then use the ObservableCollection constructor which takes and IEnumerable.
To keep your sanity you might want to break this out into a separate function!