gpt4 book ai didi

c# - 我想要做的是 FreezableCollection.AddRange(collectionToAdd)

转载 作者:行者123 更新时间:2023-11-30 22:30:08 26 4
gpt4 key购买 nike

我想做的是 FreezableCollection.AddRange(collectionToAdd)

每次我添加到 FreezableCollection 时都会引发一个事件并发生一些事情。现在我有一个我想添加的新集合,但这次我希望 FreezableCollection 的 CollectionChanged 事件 只触发一次。

循环并添加它们将为每个新项目引发事件。

有没有一种方法可以将所有目标都添加到 FreezableCollection,类似于 List.AddRange?

最佳答案

从集合派生并覆盖您想要更改的行为。我能够这样做:

public class PrestoObservableCollection<T> : ObservableCollection<T>
{
private bool _delayOnCollectionChangedNotification { get; set; }

/// <summary>
/// Add a range of IEnumerable items to the observable collection and optionally delay notification until the operation is complete.
/// </summary>
/// <param name="itemsToAdd"></param>
public void AddRange(IEnumerable<T> itemsToAdd)
{
if (itemsToAdd == null) throw new ArgumentNullException("itemsToAdd");

if (itemsToAdd.Any() == false) { return; } // Nothing to add.

_delayOnCollectionChangedNotification = true;

try
{
foreach (T item in itemsToAdd) { this.Add(item); }
}
finally
{
ResetNotificationAndFireChangedEvent();
}
}

/// <summary>
/// Clear the items in the ObservableCollection and optionally delay notification until the operation is complete.
/// </summary>
public void ClearItemsAndNotifyChangeOnlyWhenDone()
{
try
{
if (!this.Any()) { return; } // Nothing available to remove.

_delayOnCollectionChangedNotification = true;

this.Clear();
}
finally
{
ResetNotificationAndFireChangedEvent();
}
}

/// <summary>
/// Override the virtual OnCollectionChanged() method on the ObservableCollection class.
/// </summary>
/// <param name="e">Event arguments</param>
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (_delayOnCollectionChangedNotification) { return; }

base.OnCollectionChanged(e);
}

private void ResetNotificationAndFireChangedEvent()
{
// Turn delay notification off and call the OnCollectionChanged() method and tell it we had a change in the collection.
_delayOnCollectionChangedNotification = false;
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}

关于c# - 我想要做的是 FreezableCollection.AddRange(collectionToAdd),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9853064/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com