我正在制作一個檔案傳輸程式。用戶可以添加盡可能多的檔案傳輸(下載/上傳),并且這些將按 FIFO 順序進行。第一個選擇是使用Queue<T>. 這里的問題是,與 不同的是ObservableCollection,它不會自動反映 UI 中的更改。我有一個ListView控制元件,它的源設定為當前的Queue<T>,并且在執行 Enqueue() 之后,UI 不會更新。
我最好/唯一的選擇是否只是使用ObservableCollectionlike a Queue,例如在檔案傳輸完成后洗掉第一項?
public async void ExecuteRequestDownloadCommand(object commandParameter)
{
if (!(commandParameter is ModularPacket packet))
{
return;
}
foreach (FileTransferModel transfer in this.ModularPacketManager.DownloadRequest(packet))
{
FileTransferQueue.Enqueue(transfer);
}
}
<ListView x:Name="FileTransferListView" ItemsSource= "{Binding FileTransferQueue}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="Auto"/>
<GridViewColumn Header="Type" DisplayMemberBinding="{Binding Type}" Width="Auto"/>
<GridViewColumn Header="Size" DisplayMemberBinding="{Binding Size}" Width="Auto"/>
<GridViewColumn Header="Progress" DisplayMemberBinding="{Binding Progress}" Width="Auto"/>
</GridView>
</ListView.View>
</ListView>
uj5u.com熱心網友回復:
的復雜性Queue<T>.Dequeue是O(1)其中Collection<T>.RemoveAt是O(n)。這使得使用本機Queue<T>成為更好的選擇。您可以擴展Queue<T>以添加集合更改通知。
您可以使用以下實作:
public class ObservableQueue<TItem> : Queue<TItem>, INotifyCollectionChanged, INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public event NotifyCollectionChangedEventHandler? CollectionChanged;
new public void Enqueue(TItem item)
{
base.Enqueue(item);
OnPropertyChanged();
OnCollectionChanged(NotifyCollectionChangedAction.Add, item, this.Count - 1);
}
new public TItem Dequeue()
{
TItem removedItem = base.Dequeue();
OnPropertyChanged();
OnCollectionChanged(NotifyCollectionChangedAction.Remove, removedItem, 0);
return removedItem;
}
new public bool TryDequeue(out TItem? result)
{
if (base.TryDequeue(out result))
{
OnPropertyChanged();
OnCollectionChanged(NotifyCollectionChangedAction.Remove, result, 0);
return true;
}
return false;
}
new public void Clear()
{
base.Clear();
OnPropertyChanged();
OnCollectionChangedReset();
}
private void OnCollectionChanged(NotifyCollectionChangedAction action, TItem item, int index)
=> this.CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(action, item, index));
private void OnCollectionChangedReset()
=> this.CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
private void OnPropertyChanged() => this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(this.Count)));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/475809.html
