转换列表到 ObservableCollection在WP7中

发布于 2024-10-30 19:13:57 字数 355 浏览 2 评论 0原文

我不知道是否为时已晚或什么,但我不知道该怎么做...

我期望做什么,以及对象浏览器所说的,是这样的:

var oc = new ObservableCollection<T>( new List<T>() );

但是 ObservableCollection 有一个无参数构造函数。对象浏览器说有 2 个重载,其中 List 和 IEnuerable 应该能够传入。

我的设置有问题吗?手机版没有构造函数吗? (这会很奇怪)

如果这个真的不存在,那么现在使用 WP7 执行此操作的标准方法是什么?

I don't know if it's just too late or what, but I don't see how to do this...

What I'm expecting to do, and what the object browser says is there, is this:

var oc = new ObservableCollection<T>( new List<T>() );

But ObservableCollection<T> has a single parameterless constructor. The object browser says there is 2 overloads where List and IEnuerable should be able to be passed in.

Is there something wrong with my setup? Are the constructors not on the phone version? (that would be strange)

If this really doesn't exist, what is the standard way of doing this with WP7 now?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

醉南桥 2024-11-06 19:13:57

ObservableCollection 有几个构造函数,其输入参数为 List;或 IEnumerable:
列表list = new List();
ObservableCollection;集合 = new ObservableCollection(列表);

ObservableCollection has several constructors which have input parameter of List<T> or IEnumerable<T>:
List<T> list = new List<T>();
ObservableCollection<T> collection = new ObservableCollection<T>(list);

从此见与不见 2024-11-06 19:13:57

显然,您的项目针对的是 Windows Phone 7.0。不幸的是,接受 IEnumerableList在 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);

但是,如果没有必要,请不要这样做,如果您的目标框架提供重载,那么就使用它们。

Apparently, your project is targeting Windows Phone 7.0. Unfortunately the constructors that accept IEnumerable<T> or List<T> are not available in WP 7.0, only the parameterless constructor. The other constructors are available in Silverlight 4 and above and WP 7.1 and above, just not in WP 7.0.

I guess your only option is to take your list and add the items into a new instance of an ObservableCollection individually as there are no readily available methods to add them in bulk. Though that's not to stop you from putting this into an extension or static method yourself.

var list = new List<SomeType> { /* ... */ };
var oc = new ObservableCollection<SomeType>();
foreach (var item in list)
    oc.Add(item);

But don't do this if you don't have to, if you're targeting framework that provides the overloads, then use them.

云朵有点甜 2024-11-06 19:13:57

List转换为list 到可观察集合,您可以使用以下代码:

var oc = new ObservableCollection<T>();
list.ForEach(x => oc.Add(x));

To convert List<T> list to observable collection you may use following code:

var oc = new ObservableCollection<T>();
list.ForEach(x => oc.Add(x));
蓝天白云 2024-11-06 19:13:57

您必须编写自己的扩展方法才能执行此操作:

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

You'll have to write your own extension method to do this:

    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;
      }
    }
拥抱没勇气 2024-11-06 19:13:57

此答案的扩展方法 IList; ObservableCollection效果很好

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

Extension method from this answer IList<T> to ObservableCollection<T> works pretty well

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;
}
泪冰清 2024-11-06 19:13:57

使用这个:

List<Class1> myList;
ObservableCollection<Class1> myOC = new ObservableCollection<Class1>(myList);

Use this:

List<Class1> myList;
ObservableCollection<Class1> myOC = new ObservableCollection<Class1>(myList);
反目相谮 2024-11-06 19:13:57
ObservableCollection<FacebookUser_WallFeed> result = new ObservableCollection<FacebookUser_WallFeed>(FacebookHelper.facebookWallFeeds);
ObservableCollection<FacebookUser_WallFeed> result = new ObservableCollection<FacebookUser_WallFeed>(FacebookHelper.facebookWallFeeds);
强辩 2024-11-06 19:13:57

如果您要添加大量项目,请考虑从 ObservableCollection 派生您自己的类并将项目添加到受保护的 Items 成员中 - 这不会在观察者中引发事件。完成后,您可以引发适当的事件:

public class BulkUpdateObservableCollection<T> : ObservableCollection<T>
{
    public void AddRange(IEnumerable<T> collection)
    {
        foreach (var i in collection) Items.Add(i);
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        OnPropertyChanged(new PropertyChangedEventArgs("Count"));
    }
 }

将许多项添加到已绑定到 UI 元素(例如 LongListSelector)的 ObservableCollection 时,这可能会带来巨大的性能差异。

在添加项目之前,您还可以确保有足够的空间,以便通过在 BulkObservableCollection 类中实现此方法并在调用 AddRange 之前调用它来不断扩展列表:

    public void IncreaseCapacity(int increment)
    {
        var itemsList = (List<T>)Items;
        var total = itemsList.Count + increment;
        if (itemsList.Capacity < total)
        {
            itemsList.Capacity = total;
        }
    }

If you are going to be adding lots of items, consider deriving your own class from ObservableCollection and adding items to the protected Items member - this won't raise events in observers. When you are done you can raise the appropriate events:

public class BulkUpdateObservableCollection<T> : ObservableCollection<T>
{
    public void AddRange(IEnumerable<T> collection)
    {
        foreach (var i in collection) Items.Add(i);
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        OnPropertyChanged(new PropertyChangedEventArgs("Count"));
    }
 }

When adding many items to an ObservableCollection that is already bound to a UI element (such as LongListSelector) this can make a massive performance difference.

Prior to adding the items, you could also ensure you have enough space, so that the list isn't continually being expanded by implementing this method in the BulkObservableCollection class and calling it prior to calling AddRange:

    public void IncreaseCapacity(int increment)
    {
        var itemsList = (List<T>)Items;
        var total = itemsList.Count + increment;
        if (itemsList.Capacity < total)
        {
            itemsList.Capacity = total;
        }
    }
醉南桥 2024-11-06 19:13:57

我做了一个扩展,所以现在我可以通过执行以下操作来加载带有列表的集合:

MyObservableCollection.Load(MyList);

扩展名是:

public static class ObservableCollectionExtension
{
  public static ObservableCollection<T> Load<T>(this ObservableCollection<T> Collection, List<T> Source)
  {
          Collection.Clear();    
          Source.ForEach(x => Collection.Add(x));    
          return Collection;
   }
}

I made an extension so now I can just load a collection with a list by doing:

MyObservableCollection.Load(MyList);

The extension is:

public static class ObservableCollectionExtension
{
  public static ObservableCollection<T> Load<T>(this ObservableCollection<T> Collection, List<T> Source)
  {
          Collection.Clear();    
          Source.ForEach(x => Collection.Add(x));    
          return Collection;
   }
}
童话里做英雄 2024-11-06 19:13:57

Zin Min提供的答案用一行代码解决了我的问题。出色的!

我在将通用列表转换为通用 ObservableCollection 时遇到了同样的问题,以使用列表中的值来填充通过 WPF 窗口的工厂类参与绑定的组合框。

_expediteStatuses = new ObservableCollection(_db.getExpediteStatuses());

以下是 getExpediteStatuses 方法的签名:

public List; getExpediteStatuses()

The answer provided by Zin Min solved my problem with a single line of code. Excellent!

I was having the same issue of converting a generic List to a generic ObservableCollection to use the values from my List to populate a ComboBox that is participating in binding via a factory class for a WPF Window.

_expediteStatuses = new ObservableCollection<ExpediteStatus>(_db.getExpediteStatuses());

Here is the signature for the getExpediteStatuses method:

public List<ExpediteStatus> getExpediteStatuses()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文