我有一个名为CustomerService的类,它只是从文件中读取客户的集合或创建一个客户,然后将其传递回主模型视图,并将其转换为ObservableCollection。确保CustomerService和ObservableCollection中的项目保持同步的最佳做法是什么。我猜我可以连接CustomerService对象来响应RaisePropertyChanged,但这不仅仅是用于WPF控件吗?还有更好的方法吗?
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;
}
}
答案 0 :(得分:2)
处理“客户”的CollectionChanged事件。如果更改,请致电您的服务以保持同步。
绑定“客户”时,请确保在xaml中指定“Mode = TwoWay”。