How do I keep my DataService up to date with ObservableCollection?
Posted
by joebeazelman
on Stack Overflow
See other posts from Stack Overflow
or by joebeazelman
Published on 2010-05-04T17:17:26Z
Indexed on
2010/05/04
17:18 UTC
Read the original article
Hit count: 246
I have a class called CustomerService which simply reads a collection of customers from a file or creates one and passes it back to the Main Model View where it is turned into an ObservableCollection. What the best practice for making sure the items in the CustomerService and ObservableCollection are in sync. I'm guessing I could hookup the CustomerService object to respond to RaisePropertyChanged, but isn't this only for use with WPF controls? Is there a better way?
using System;
public class MainModelView
{
public MainModelView()
{
_customers = new ObservableCollection<CustomerViewModel>(new CustomerService().GetCustomers());
}
public const string CustomersPropertyName = "Customers"
private ObservableCollection<CustomerViewModel> _customers;
public ObservableCollection<CustomerViewModel> Customers
{
get
{
return _customers;
}
set
{
if (_customers == value)
{
return;
}
var oldValue = _customers;
_customers = value;
// Update bindings and broadcast change using GalaSoft.MvvmLight.Messenging
RaisePropertyChanged(CustomersPropertyName, oldValue, value, true);
}
}
}
public class CustomerService
{
/// <summary>
/// Load all persons from file on disk.
/// </summary>
_customers = new List<CustomerViewModel>
{
new CustomerViewModel(new Customer("Bob", "" )),
new CustomerViewModel(new Customer("Bob 2", "" )),
new CustomerViewModel(new Customer("Bob 3", "" )),
};
public IEnumerable<LinkViewModel> GetCustomers()
{
return _customers;
}
}
© Stack Overflow or respective owner