gurehbgui
gurehbgui

Reputation: 14674

why my ObservableCollection is not refreshed in the ListBox?

I have a problem with my code. I use a listbox and a observable collection to add the data to the list. the code looks like this:

ListData actualData;
ObservableCollection<ListData> data;

public Calculate()
{
    InitializeComponent();

    data = new ObservableCollection<ListData>();
    newData();

    listbox1.ItemsSource = data;
}

private void newData()
{
    actualData = new ListData("1", "2", "3");
    data.Add(actualData);
}

Now, I have a button which, for example, changes actualData but I cant see the change in the list.

the button looks like:

private void button1_Click(object sender, RoutedEventArgs e)
{
    actualData.first = "12";
}

I found a workaround:

listbox1.ItemsSource = null;
listbox1.ItemsSource = data;

but this is not a good solution, what is wrong here?

Upvotes: 0

Views: 315

Answers (2)

Adam
Adam

Reputation: 15805

As ZafarYousafi has correctly stated in his answer, ObservableCollection<T> will only notify the list of added and removed items; if you change a property on one of the items, it won't be updated in the list.

Instead, you need to change your ListData class's definition like so:

public class ListData : INotifyPropertyChanged

This requires your class to implement the PropertyChanged event:

public event PropertyChangedEventHandler PropertyChanged;

Now, all you need to do is change your definition of first (coding conventions dictate that properties should start with a capital letter, PascalCase):

private string first;
public string First
{
    get { return first; }
    set
    {
        first = value;
        var handler = PropertyChanged; //according to Essential C# (M. Michaelis) 
        if (handler != null)           //the copy should prevent threading issues
        {                              
            handler(this, new PropertyChangedEventArgs("First"));
        }
    }
}

By the way: I feel uncomfortable about having to pass in the property name as a string. For a more sophisticated solution, see this tutorial.

Upvotes: 3

ZafarYousafi
ZafarYousafi

Reputation: 10840

ObservableCollection will only notify when there is an activity on the list and not on the item of the list. Activity on list means adding/removing items in the list. You need to implement INotifyPropertyChange interface to ListData class to notify the changes in the ListData class properties/members.

Upvotes: 4

Related Questions