views:

123

answers:

1

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;
        }
}
+2  A: 

Handle the CollectionChanged event of "Customers". When it changes, call your service to keep it synced.

When binding your "Customers" make sure you specify "Mode=TwoWay" in your xaml.

vidalsasoon