New Developer
New Developer

Reputation: 3305

ObservableCollection does not update

I have ObservableCollection<Customer> on my window.

ObservableCollection<Customer> customers = new ObservableCollection<Customer>();
public ObservableCollection<Customer> Customers { get { return customers; } set { customers = value; OnPropertyChanged("Customers"); } }  

This ObservableCollection has bound to ListView on the window. Once Use select on Customer from listView and click on edit a new window will appear with selected customer's data.

Second window's constructor

public EditCustomerWindow(Customer c)
{
    InitializeComponent();

    customerobj = c; //Original object
    tempCustomerobj = new Customer(c); //Getting a copy of the customer object

    CustomerDataGrid.DataContext = tempCustomerobj;
}  

Once user clicks on Save Button customer object will get updated and window will closes.

But my issue is ObserverCollection does not get update on fist window even though I set new edited customer object before editing window get closed. Cannot find what is the wrong I am doing. Please advice me.

customerobj = tempCustomerobj;

Upvotes: 1

Views: 353

Answers (1)

Eric J.
Eric J.

Reputation: 150108

You appear to be creating a new Customer object that is not in your ObservableCollection

tempCustomerobj = new Customer(c);

and then editing that new object.

CustomerDataGrid.DataContext = tempCustomerobj;

Doing that will not in any way affect the original Customer object that is still in your ObservableCollection.

To solve, don't create a new Customer, but rather edit an existing one.

Update

Based on your comments

The line

customerobj = c; //Original object

causes customerobj to be an alias to c, your object that is actually in the ObservableCollection.

The line

customerobj = tempCustomerobj;

causes customerobj to now be an alias to tempCustomerobj, which is your brand-new Customer object that is (I presume) a clone of c.

Change your constructor to

public EditCustomerWindow(Customer c)
{
    InitializeComponent();

    CustomerDataGrid.DataContext = c;
}  

Update 2

The object you're editing should support IEditableObject. See

https://stackoverflow.com/a/1091240/141172

Alternatively, you can serialize the object before you start editing and deserialize the saved state if the edit is canceled.

Upvotes: 2

Related Questions