以下Source绑定到Grid的Items Source属性,并且不知道为什么不能进行此转换;我收到以下错误:"无法将List类型的对象强制转换为IList。"有什么不对,在这种情况下会有什么工作?
public IList<TypeTwo> Source { get; set; }
public SomeViewModel()
{
List<TypeOne> result = db.GetInfo().ToList();
Source = (IList<TypeTwo>)result;
// This works if the IList is of Type TypeOne
// Source = db.GetInfo().ToList();
}
public class TypeTwo {
// The same properties of TypeOne
}
答案 0 :(得分:2)
您必须单独转换每个元素,而不是一次转换整个列表:
Source = result
.Select(x => new TypeTwo()
{
SharedProperty1 = x.SharedProperty1,
SharedProperty2 = x.SharedProperty2,
....
})
.ToList();
// only if TypeTwo derives from TypeOne, or implements an explicit cast operator
//Source = result.Cast<TypeTwo>().ToList();