.net 中 ObservableCollection 有什么用?

发布于 2024-10-04 01:51:29 字数 40 浏览 5 评论 0原文

.net 中 ObservableCollection 有什么用?

What is the use of ObservableCollection in .net?

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

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

发布评论

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

评论(8

〆凄凉。 2024-10-11 01:51:29

ObservableCollection 是一个集合,允许集合外部的代码了解集合何时发生更改(添加、移动、删除)。它在 WPF 和 Silverlight 中大量使用,但其用途并不限于此。代码可以添加事件处理程序来查看集合何时发生更改,然后通过事件处理程序做出反应以执行一些其他处理。这可能会更改 UI 或执行某些其他操作。

下面的代码实际上并没有做任何事情,而是演示了如何在类中附加处理程序,然后使用事件参数以某种方式对更改做出反应。 WPF 已经内置了许多操作,例如刷新 UI,因此您在使用 ObservableCollections 时可以免费获得它们

class Handler
{
    private ObservableCollection<string> collection;

    public Handler()
    {
        collection = new ObservableCollection<string>();
        collection.CollectionChanged += HandleChange;
    }

    private void HandleChange(object sender, NotifyCollectionChangedEventArgs e)
    {
        foreach (var x in e.NewItems)
        {
            // do something
        }

        foreach (var y in e.OldItems)
        {
            //do something
        }
        if (e.Action == NotifyCollectionChangedAction.Move)
        {
            //do something
        }
    }
}

ObservableCollection is a collection that allows code outside the collection be aware of when changes to the collection (add, move, remove) occur. It is used heavily in WPF and Silverlight but its use is not limited to there. Code can add event handlers to see when the collection has changed and then react through the event handler to do some additional processing. This may be changing a UI or performing some other operation.

The code below doesn't really do anything but demonstrates how you'd attach a handler in a class and then use the event args to react in some way to the changes. WPF already has many operations like refreshing the UI built in so you get them for free when using ObservableCollections

class Handler
{
    private ObservableCollection<string> collection;

    public Handler()
    {
        collection = new ObservableCollection<string>();
        collection.CollectionChanged += HandleChange;
    }

    private void HandleChange(object sender, NotifyCollectionChangedEventArgs e)
    {
        foreach (var x in e.NewItems)
        {
            // do something
        }

        foreach (var y in e.OldItems)
        {
            //do something
        }
        if (e.Action == NotifyCollectionChangedAction.Move)
        {
            //do something
        }
    }
}
眼前雾蒙蒙 2024-10-11 01:51:29

ObservableCollection 的工作原理本质上就像常规收集,除了它实现
接口:

因此,当您想要知道集合何时发生更改。触发一个事件,告诉用户哪些条目已添加/删除或移动。

更重要的是,它们在表单上使用数据绑定时非常有用。

An ObservableCollection works essentially like a regular collection except that it implements
the interfaces:

As such it is very useful when you want to know when the collection has changed. An event is triggered that will tell the user what entries have been added/removed or moved.

More importantly they are very useful when using databinding on a form.

独守阴晴ぅ圆缺 2024-10-11 01:51:29

来自 Pro C# 5.0 和 .NET 4.5 Framework

ObservableCollection 类非常有用,因为它能够通知外部对象
当它的内容以某种方式改变时(正如你可能猜到的那样,使用
ReadOnlyObservableCollection 非常相似,但本质上是只读的)。
在许多方面,与
ObservableCollection 与使用 List 相同,因为这两个类
实现相同的核心接口。 ObservableCollection 类的独特之处在于:
类支持名为 CollectionChanged 的事件。每当插入新项目、删除(或重新定位)当前项目或修改整个集合时,都会触发此事件。
与任何事件一样,CollectionChanged 是根据委托定义的,在本例中是
NotifyCollectionChangedEventHandler。此委托可以调用任何将对象作为第一个参数、将 NotifyCollectionChangedEventArgs 作为第二个参数的方法。考虑下面的 Main()
方法,它填充一个包含 Person 对象的可观察集合并连接
CollectionChanged 事件:

class Program
{
   static void Main(string[] args)
   {
     // Make a collection to observe and add a few Person objects.
     ObservableCollection<Person> people = new ObservableCollection<Person>()
     {
        new Person{ FirstName = "Peter", LastName = "Murphy", Age = 52 },
        new Person{ FirstName = "Kevin", LastName = "Key", Age = 48 },
     };
     // Wire up the CollectionChanged event.
     people.CollectionChanged += people_CollectionChanged;
     // Now add a new item.
     people.Add(new Person("Fred", "Smith", 32));

     // Remove an item.
     people.RemoveAt(0);

     Console.ReadLine();
   }
   static void people_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
   {
       // What was the action that caused the event?
        Console.WriteLine("Action for this event: {0}", e.Action);

        // They removed something. 
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
        {
            Console.WriteLine("Here are the OLD items:");
            foreach (Person p in e.OldItems)
            {
                Console.WriteLine(p.ToString());
            }
            Console.WriteLine();
        }

        // They added something. 
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
        {
            // Now show the NEW items that were inserted.
            Console.WriteLine("Here are the NEW items:");
            foreach (Person p in e.NewItems)
            {
                Console.WriteLine(p.ToString());
            }
        }
   }
}

传入的 NotifyCollectionChangedEventArgs 参数定义了两个重要的属性,
OldItemsNewItems,这将为您提供事件触发之前集合中当前项目的列表,以及更改中涉及的新项目。但是,您只需要在正确的情况下检查这些列表。回想一下,CollectionChanged 事件可以在以下情况下触发:
添加、删除、重新定位或重置项目。要发现哪些操作触发了事件,
您可以使用 NotifyCollectionChangedEventArgs 的 Action 属性。 Action 属性可以是
针对 NotifyCollectionChangedAction 枚举的以下任何成员进行了测试:

public enum NotifyCollectionChangedAction
{
Add = 0,
Remove = 1,
Replace = 2,
Move = 3,
Reset = 4,
}

Members of System.Collections.ObjectModel

From Pro C# 5.0 and the .NET 4.5 Framework

The ObservableCollection<T> class is very useful in that it has the ability to inform external objects
when its contents have changed in some way (as you might guess, working with
ReadOnlyObservableCollection<T> is very similar, but read-only in nature).
In many ways, working with
the ObservableCollection<T> is identical to working with List<T>, given that both of these classes
implement the same core interfaces. What makes the ObservableCollection<T> class unique is that this
class supports an event named CollectionChanged. This event will fire whenever a new item is inserted, a current item is removed (or relocated), or if the entire collection is modified.
Like any event, CollectionChanged is defined in terms of a delegate, which in this case is
NotifyCollectionChangedEventHandler. This delegate can call any method that takes an object as the first parameter, and a NotifyCollectionChangedEventArgs as the second. Consider the following Main()
method, which populates an observable collection containing Person objects and wires up the
CollectionChanged event:

class Program
{
   static void Main(string[] args)
   {
     // Make a collection to observe and add a few Person objects.
     ObservableCollection<Person> people = new ObservableCollection<Person>()
     {
        new Person{ FirstName = "Peter", LastName = "Murphy", Age = 52 },
        new Person{ FirstName = "Kevin", LastName = "Key", Age = 48 },
     };
     // Wire up the CollectionChanged event.
     people.CollectionChanged += people_CollectionChanged;
     // Now add a new item.
     people.Add(new Person("Fred", "Smith", 32));

     // Remove an item.
     people.RemoveAt(0);

     Console.ReadLine();
   }
   static void people_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
   {
       // What was the action that caused the event?
        Console.WriteLine("Action for this event: {0}", e.Action);

        // They removed something. 
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
        {
            Console.WriteLine("Here are the OLD items:");
            foreach (Person p in e.OldItems)
            {
                Console.WriteLine(p.ToString());
            }
            Console.WriteLine();
        }

        // They added something. 
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
        {
            // Now show the NEW items that were inserted.
            Console.WriteLine("Here are the NEW items:");
            foreach (Person p in e.NewItems)
            {
                Console.WriteLine(p.ToString());
            }
        }
   }
}

The incoming NotifyCollectionChangedEventArgs parameter defines two important properties,
OldItems and NewItems, which will give you a list of items that were currently in the collection before the event fired, and the new items that were involved in the change. However, you will want to examine these lists only under the correct circumstances. Recall that the CollectionChanged event can fire when
items are added, removed, relocated, or reset. To discover which of these actions triggered the event,
you can use the Action property of NotifyCollectionChangedEventArgs. The Action property can be
tested against any of the following members of the NotifyCollectionChangedAction enumeration:

public enum NotifyCollectionChangedAction
{
Add = 0,
Remove = 1,
Replace = 2,
Move = 3,
Reset = 4,
}

Members of System.Collections.ObjectModel

謌踐踏愛綪 2024-10-11 01:51:29

没有代码的解释

对于那些想要一个没有任何代码(繁荣)和一个故事(帮助您记住)的答案的人:

普通收藏 - 无通知

我时不时地去纽约和我的老婆叫我去买东西。所以我随身带着一份购物清单。清单上有很多东西,例如:

  1. Louis Vuitton 手提包(5000 美元)
  2. Dior 香水(400 美元)
  3. Gucci 太阳镜(2000 美元)

好吧,我不买那些东西。所以我将它们划掉并将其从清单中删除,然后添加相反:

  1. 12 打 Titleist 高尔夫球。

所以我通常没有带货

The ObservableCollection - 进行更改时的通知

现在,每当我从列表中删除某些内容时:她都会收到一条通知

“Observable Collection”有效 。同样,如果您向其中添加或删除某些内容:

请注意,结果是可以通过事件处理程序自定义的,

但是为什么呢?

当他们收到通知时, 必须实现 INotifyPropertyChanged - 但这是通过 ObservableCollections 自动完成的。

注意:如果您修改集合中的项目 - 则不会触发更改事件

,但希望您会记住这个概念。

Explanation without Code

For those wanting an answer without any code behind it (boom-tish) with a story (to help you remember):

Normal Collections - No Notifications

Every now and then I go to NYC and my wife asks me to buy stuff. So I take a shopping list with me. The list has a lot of things on there like:

  1. Louis Vuitton handbag ($5000)
  2. Dior Perfume ($400 )
  3. Gucci Sunglasses ($2000)

well I"m not buying that stuff. So I cross them off and remove them from the list and I add instead:

  1. 12 dozen Titleist golf balls.

So I usually come home without the goods.

The ObservableCollection - notifications when changes made

Now, whenever I remove something from the list: she get's a notification.

The observable collection works just the same way. If you add or remove something to or from it: someone is notified.

And when they are notified, watch out! Of course, the consequences are customisable via an event handler.

But why?

Normally, when something changes you would have to implement INotifyPropertyChanged - but this is automatically done for you with ObservableCollections.

Note: If you modify an item within a collection - then no change event is triggered.

Silly story, but hopefully you'll remember the concept.

匿名的好友 2024-10-11 01:51:29

最大的用途之一是您可以将 UI 组件绑定到其中,并且如果集合的内容发生更改,它们将做出适当的响应。例如,如果将 ListView 的 ItemsSource 绑定到其中一个,则在修改集合时 ListView 的内容将自动更新。

编辑:
以下是来自 MSDN 的一些示例代码:
http://msdn.microsoft.com/en-us/library/ms748365.aspx

在 C# 中,将 ListBox 挂接到集合可能很简单,就好像

listBox.ItemsSource = NameListData;

您尚未将列表挂接到静态资源并定义 NameItemTemplate 一样,您可能想要覆盖 PersonName 的 ToString()。例如:

public override ToString()
{
    return string.Format("{0} {1}", this.FirstName, this.LastName);
}

One of the biggest uses is that you can bind UI components to one, and they'll respond appropriately if the collection's contents change. For example, if you bind a ListView's ItemsSource to one, the ListView's contents will automatically update if you modify the collection.

EDIT:
Here's some sample code from MSDN:
http://msdn.microsoft.com/en-us/library/ms748365.aspx

In C#, hooking the ListBox to the collection could be as easy as

listBox.ItemsSource = NameListData;

though if you haven't hooked the list up as a static resource and defined NameItemTemplate you may want to override PersonName's ToString(). For example:

public override ToString()
{
    return string.Format("{0} {1}", this.FirstName, this.LastName);
}
在风中等你 2024-10-11 01:51:29

它是一个集合,用于通知集合中大部分UI发生变化,它支持自动通知。

主要用在 WPF 中,

假设您有一个带有列表框和添加按钮的 UI,当您单击按钮时,假设 person 类型的对象将被添加到 obseravablecollection 中,并且您将此集合绑定到 Listbox 的 ItemSource ,如下所示一旦您在集合中添加了一个新项目,列表框就会自行更新并在其中添加一个新项目。

it is a collection which is used to notify mostly UI to change in the collection , it supports automatic notification.

Mainly used in WPF ,

Where say suppose you have UI with a list box and add button and when you click on he button an object of type suppose person will be added to the obseravablecollection and you bind this collection to the ItemSource of Listbox , so as soon as you added a new item in the collection , Listbox will update itself and add one more item in it.

赠佳期 2024-10-11 01:51:29
class FooObservableCollection : ObservableCollection<Foo>
{
    protected override void InsertItem(int index, Foo item)
    {
        base.Add(index, Foo);

        if (this.CollectionChanged != null)
            this.CollectionChanged(this, new NotifyCollectionChangedEventArgs (NotifyCollectionChangedAction.Add, item, index);
    }
}

var collection = new FooObservableCollection();
collection.CollectionChanged += CollectionChanged;

collection.Add(new Foo());

void CollectionChanged (object sender, NotifyCollectionChangedEventArgs e)
{
    Foo newItem = e.NewItems.OfType<Foo>().First();
}
class FooObservableCollection : ObservableCollection<Foo>
{
    protected override void InsertItem(int index, Foo item)
    {
        base.Add(index, Foo);

        if (this.CollectionChanged != null)
            this.CollectionChanged(this, new NotifyCollectionChangedEventArgs (NotifyCollectionChangedAction.Add, item, index);
    }
}

var collection = new FooObservableCollection();
collection.CollectionChanged += CollectionChanged;

collection.Add(new Foo());

void CollectionChanged (object sender, NotifyCollectionChangedEventArgs e)
{
    Foo newItem = e.NewItems.OfType<Foo>().First();
}
谈下烟灰 2024-10-11 01:51:29

ObservableCollection 警告

上面提到的(Roohullah Allem 所说)

ObservableCollection 类的独特之处在于
类支持名为 CollectionChanged 的​​事件。

请记住这一点...如果您向 ObservableCollection 添加大量项目,UI 也会更新多次。这真的会搞乱或冻结你的用户界面。
解决方法是创建一个新列表,添加所有项目,然后将您的属性设置为新列表。这会影响 UI 一次。再次...这是为了添加大量项目。

ObservableCollection Caveat

Mentioned above (Said Roohullah Allem)

What makes the ObservableCollection class unique is that this
class supports an event named CollectionChanged.

Keep this in mind...If you adding a large number of items to an ObservableCollection the UI will also update that many times. This can really gum up or freeze your UI.
A work around would be to create a new list, add all the items then set your property to the new list. This hits the UI once. Again...this is for adding a large number of items.

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