2010-11-24 31 views
8

我将ListBox绑定为Queue<string>。当我入队/出队物品时,ListBox不会更新。绑定到队列<string>。 UI永不更新

我有入队/出队的助手,以提高性能变化

protected void EnqueueWork(string param) 
{ 
    Queue.Enqueue(param); 
    RaisePropertyChanged("Queue"); 
} 

protected string DequeueWork() 
{ 
    string tmp = Queue.Dequeue(); 
    RaisePropertyChanged("Queue"); 
    return tmp; 
} 
+0

你怎么绑定列表框到一个队列?我得到一个错误,说它需要绑定到IList或IListSource – vkapadia 2017-06-30 18:46:20

回答

25

你有没有实施INotifyCollectionChanged?您需要使用此操作来通知添加或删除集合中的项目等操作。

这里是队列一个简单的实现:

public class ObservableQueue<T> : INotifyCollectionChanged, IEnumerable<T> 
{ 
    public event NotifyCollectionChangedEventHandler CollectionChanged; 
    private readonly Queue<T> queue = new Queue<T>(); 

    public void Enqueue(T item) 
    { 
     queue.Enqueue(item); 
     if (CollectionChanged != null) 
      CollectionChanged(this, 
       new NotifyCollectionChangedEventArgs(
        NotifyCollectionChangedAction.Add, item)); 
    } 

    public T Dequeue() 
    { 
     var item = queue.Dequeue(); 
     if (CollectionChanged != null) 
      CollectionChanged(this, 
       new NotifyCollectionChangedEventArgs(
        NotifyCollectionChangedAction.Remove, item)); 
     return item; 
    } 

    public IEnumerator<T> GetEnumerator() 
    { 
     return queue.GetEnumerator(); 
    } 

    IEnumerator IEnumerable.GetEnumerator() 
    { 
     return GetEnumerator(); 
    } 
} 
1

您应该使用的ObservableCollection不排队做你想做的,允许列表框对项目添加和删除你的类应该实现INotifyCollectionChanged更新,的ObservableCollection实现该接口,或者您也可以编写自定义队列(ObservableQueue)实现INotifyCollectionChanged接口

This post可以帮助

+0

是否从我的窗口(数据上下文)引发属性更改不够?我可以用int来做同样的事情,我认为这是不可观察的?我之所以想要使用队列的原因是因为使用,我只需要入队和出队的东西,但它确定,我可以使用`ObservableCollection`仍然 – 2010-11-24 12:23:28

+0

哦,顺便说一句,我将如何扩展Queue类来使它观察到的?我试图扩展`Queue `,然后当我想要覆盖Enqueue时,我不知道该写什么 – 2010-11-24 12:35:16