ProfK
ProfK

Reputation: 51104

How do I refresh an Observable collection bound to a WPF DataGrid?

I first tried this:

var users = await _service.Read();
var usersTemp = users as IList<UserDto> ?? users.ToList();
usersTemp.ToList().ForEach(u =>
{
    if (usersTemp.Contains(u))
    {
        var good = Users.Remove(u);
    }
    Users.Add(u);
});

I only have one user, to test, but every time I execute the above code, that user gets added to the collection. I added good and found Remove was not working.

Now it's down to re-creating the collection when I actually only want to refresh it:

Users = new ObservableCollection<UserDto>(await _service.Read());
OnPropertyChanged(nameof(Users));

How can I do this better? I want to be able to add new users to the collection when I receive a SignalR notification, not do another relatively expensive Get and recreate the collection.

Upvotes: 2

Views: 810

Answers (1)

Nkosi
Nkosi

Reputation: 247551

Remove works with the actual object in the collection. The contains in OP is trying to compare an object that was not originally in the list. Try finding the desired object using some identifier and then replacing the object if found. otherwise add it to the list.

usersTemp.ToList().ForEach(u => {
    var user = Users.FirstOrDefault(x => x.ID == u.ID);
    if (user != null) {//User already exists
        var index = Users.IndexOf(user);//get its location in list
        Users[index] = u;//replace it with new object
    } else {
        Users.Add(u);
    }
});

Upvotes: 1

Related Questions