开发者

How do I keep my DataService up to date with ObservableCollection?

开发者 https://www.devze.com 2022-12-29 07:12 出处:网络
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.

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().Ge开发者_JAVA技巧tCustomers());
    }

    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;
        }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号