具有Observablecollection的依赖属性

时间:2013-11-05 20:19:09

标签: c# linq linq-to-sql

    public IEnumerable<Location> Locations
    {
        get { return (IEnumerable<Location>)GetValue(LocationsProperty); }
        set { SetValue(LocationsProperty, value); }
    }

    public static readonly DependencyProperty LocationsProperty =
        DependencyProperty.Register("Locations", typeof(IEnumerable<Location>), typeof(userControl), new PropertyMetadata(null));  




  public class Location
    {
        public db.Location DbLocation { get; set; }
        public ObservableCollection<db.Person> DbContactsInLocation { get; set; }
    }

    Locations = myDataContext.Locations
       .Where(l => l.Active == "Y")
       .OrderBy(l => l.Name)
       .Select(l => new Location { 
               DbLocation = l
               **DbContactsInLocation = l.PersonLocations.Select(pl => pl.personLocation.person)**
                }).ToList();

我得到了:

  

无法隐式转换类型   System.Collections.Generic.IEnumerable <myDataContext.Person>' to   “System.Collections.ObjectModel.ObservableCollection <myDataContext.Person>'   存在显式转换(您是否错过了演员?)

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您需要将LINQ查询插入ObservableCollection<T>(IEnumerable<T>)构造函数。试试这个:

DBContactsInLocation = new ObservableCollection<myDataContext.Person>(l.PersonLocations.Select(pl => pl.personLocation.person).ToList());

答案 1 :(得分:1)

将您的linq查询换入ObservableCollection<T>(IEnumerabele<T>) constructor

DbContactsInLocation = new ObservableCollection<db.Person>(
  l.PersonLocations.Select(pl => pl.personLocation.person)
)