1. 程式人生 > >(MVVM) ListBox Binding

(MVVM) ListBox Binding

ado 還需要 nbsp pro 完成 protected don his see

當需要用Lisbbox 來log 一些記錄的時候,ObservableCollection 並不可以是記錄實時的反應在WPF 的UI上面。

這個時候就需要用一個異步collection 來完成。

    /// <summary>
    /// Represents the asynchronous observable collection.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class AsyncObservableCollection<T> : ObservableCollection<T>
    {
        
/// <summary> /// The _synchronization context /// </summary> private readonly SynchronizationContext synchronizationContext = SynchronizationContext.Current; /// <summary> /// Initializes a new instance of the <see cref="AsyncObservableCollection{T}"/>
class. /// </summary> public AsyncObservableCollection() { } /// <summary> /// Initializes a new instance of the <see cref="AsyncObservableCollection{T}"/> class. /// </summary> /// <param name="list">The list.</param>
public AsyncObservableCollection(IEnumerable<T> list) : base(list) { } /// <summary> /// Inserts the item. /// </summary> /// <param name="index">The index.</param> /// <param name="item">The item.</param> protected override void InsertItem(int index, T item) { this.ExecuteOnSyncContext(() => base.InsertItem(index, item)); } /// <summary> /// Removes the item. /// </summary> /// <param name="index">The index.</param> protected override void RemoveItem(int index) { this.ExecuteOnSyncContext(() => base.RemoveItem(index)); } /// <summary> /// Sets the item. /// </summary> /// <param name="index">The index.</param> /// <param name="item">The item.</param> protected override void SetItem(int index, T item) { this.ExecuteOnSyncContext(() => base.SetItem(index, item)); } /// <summary> /// Moves the item. /// </summary> /// <param name="oldIndex">The old index.</param> /// <param name="newIndex">The new index.</param> protected override void MoveItem(int oldIndex, int newIndex) { this.ExecuteOnSyncContext(() => base.MoveItem(oldIndex, newIndex)); } /// <summary> /// Clears the items. /// </summary> protected override void ClearItems() { this.ExecuteOnSyncContext(() => base.ClearItems()); } /// <summary> /// Executes the on synchronize context. /// </summary> /// <param name="action">The action.</param> private void ExecuteOnSyncContext(Action action) { if (SynchronizationContext.Current == this.synchronizationContext) { action(); } else { this.synchronizationContext.Send(_ => action(), null); } } }

另外還需要啟用一個新的線程來更新collection

(MVVM) ListBox Binding