我正在将项目从 Windows 窗体转换为 WPF 格式。目前,我已将所有数据绑定到元素。我现在提出一个问题ObservableCollection
,说:
这种类型的 CollectionView 不支持从不同于 Dispatcher 线程的线程更改其 SourceCollection。
如何使我的代码线程安全?或者我如何引导对 Dispatcher 线程的更改?我看过一些关于它的帖子,但我对如何在我自己的项目中应用它感到困惑。也许有人可以为我阐明这一点?
这是我的代码ObservableList.cs
:
public class ObservableList<T> : ObservableCollection<T>
{
#region Private members
bool isInAddRange = false;
#endregion Private members
#region Public methods
/// <summary>
/// Creates a new empty ObservableList of the provided type.
/// </summary>
public ObservableList()
{
}
/// <summary>
/// Handles the event when a collection has changed.
/// </summary>
/// <param name="e"></param>
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
// intercept this when it gets called inside the AddRange method.
if (!isInAddRange)
base.OnCollectionChanged(e);
}
/// <summary>
/// Adds a collection of items to the ObservableList.
/// </summary>
/// <param name="items"></param>
public void AddRange(IEnumerable<T> items)
{
isInAddRange = true;
foreach (T item in items)
{
Add(item);
}
isInAddRange = false;
var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add,items.ToList());
base.OnCollectionChanged(e);
}
#endregion Public methods
}
}
编辑:在 ywm 给出答案后,我将AddRange
班级更改为:
public void AddRange(IEnumerable<T> items)
{
isInAddRange = true;
foreach (T item in items)
{
if (item != null)
{
Dispatcher.CurrentDispatcher.Invoke((Action)(() =>
{
Add(item);
}));
}
}
isInAddRange = false;
var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add,items.ToList());
base.OnCollectionChanged(e);
}
现在,我所有的 ObservableList 都是null
.