Jos*_*ose 41 .net c# collections windows-phone-7
我不知道是否为时已晚或是什么,但我不知道如何做到这一点......
我期待做什么,以及对象浏览器所说的内容是:
var oc = new ObservableCollection<T>( new List<T>() );
Run Code Online (Sandbox Code Playgroud)
但是ObservableCollection<T>有一个无参数的构造函数.对象浏览器说有2个重载,其中List和IEnuerable应该能够传入.
我的设置有问题吗?构造函数不在手机版本上吗?(那会很奇怪)
如果这确实不存在,那么现在使用WP7的标准方法是什么?
eug*_*kov 102
ObservableCollection有几个构造函数,它们的输入参数为List <T>或IEnumerable <T>:
List<T> list = new List<T>();
ObservableCollection<T> collection = new ObservableCollection<T>(list);
Jef*_*ado 34
构造函数IEnumerable<T>和List<T>在WP 7.0,不支持.WP 7.0中仅支持无参数构造函数.其他构造函数在Silverlight 4及更高版本以及WP 7.1及更高版本中可用,而不是在WP 7.0中.
我想您唯一的选择是获取您的列表并将项目添加到ObservableCollection单独的新实例中,因为没有现成的方法可以批量添加它们.虽然这不是阻止你自己把它放入扩展或静态方法.
var list = new List<SomeType> { /* ... */ };
var oc = new ObservableCollection<SomeType>();
foreach (var item in list)
oc.Add(item);
Run Code Online (Sandbox Code Playgroud)
Iva*_*alo 14
要转换List<T> list为可观察的集合,您可以使用以下代码:
var oc = new ObservableCollection<T>();
list.ForEach(x => oc.Add(x));
Run Code Online (Sandbox Code Playgroud)
您必须编写自己的扩展方法来执行此操作:
public static class CollectionEx
{
/// <summary>
/// Copies the contents of an IEnumerable list to an ObservableCollection
/// </summary>
/// <typeparam name="T">The type of objects in the source list</typeparam>
/// <param name="enumerableList">The source list to be converted</param>
/// <returns>An ObservableCollection containing the objects from the source list</returns>
public static ObservableCollection<T> ToObservableCollection<T>( this IEnumerable<T> enumerableList )
{
if( enumerableList != null ) {
// Create an emtpy observable collection object
var observableCollection = new ObservableCollection<T>();
// Loop through all the records and add to observable collection object
foreach( var item in enumerableList ) {
observableCollection.Add( item );
}
// Return the populated observable collection
return observableCollection;
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
从这个答案IList <T>到ObservableCollection <T>的扩展方法非常有效
public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerable) {
var col = new ObservableCollection<T>();
foreach ( var cur in enumerable ) {
col.Add(cur);
}
return col;
}
Run Code Online (Sandbox Code Playgroud)
小智 6
ObservableCollection<FacebookUser_WallFeed> result = new ObservableCollection<FacebookUser_WallFeed>(FacebookHelper.facebookWallFeeds);
Run Code Online (Sandbox Code Playgroud)
用这个:
List<Class1> myList;
ObservableCollection<Class1> myOC = new ObservableCollection<Class1>(myList);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
90149 次 |
| 最近记录: |