Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding to Queue<string>. UI never updates

Tags:

c#

queue

I bound a ListBox to a Queue<string>. When I enqueue/dequeue items, the ListBox does not update.

I have helpers for enqueue/dequeue to raise property change

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

protected string DequeueWork()
{
    string tmp = Queue.Dequeue();
    RaisePropertyChanged("Queue");
    return tmp;
} 
like image 886
Jiew Meng Avatar asked Nov 24 '10 12:11

Jiew Meng


2 Answers

Have you implemented INotifyCollectionChanged ? you need this for notifications of actions like adding or removing items from a collection.

here is a simple implementation for queue:

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();
    }
}
like image 64
Dean Chalk Avatar answered Sep 28 '22 06:09

Dean Chalk


You should use ObservableCollection not queue to do what you want, to allow ListBox to update on items adding and removing your class should implement INotifyCollectionChanged, ObservableCollection implements that interface, Or you can write your custom queue (ObservableQueue) that implements INotifyCollectionChanged interface

This post can help

like image 42
Arsen Mkrtchyan Avatar answered Sep 28 '22 04:09

Arsen Mkrtchyan