我搜索了整个互联网寻找没有结果的解决方案。
在我的程序中,我有 UI 线程,在两个数据网格“客户”和“订单”中显示。显示所选客户的订单。集合的定义及其更新在后台进行。 UI 的目的只是显示最新信息。我利用 C# 4.5 中引入的最新功能,即:BindingOperations.EnableCollectionSynchronization 方法。
在我的程序中,我有一个 Customers 类,它定义了 Customer 类的集合。反过来,Customer 类定义了 Order 类的集合。我的问题是我不知道如何正确编码下面代码的最后一行这涉及到订单集合绑定同步。此代码经过简化,我省略了 OnPropertyChange 代码行以确保数据网格中显示正确的属性 - 我想专注于集合。
public class Customers()
{
private ObservableCollection<Customer> _customerslist;
public ObservableCollection<Customer> customerslist
{get {
if (_customerslist == null)
{_customerslist = new ObservableCollection<Customer>();}
return _customerslist;
}private set
{_customerslist = value;}}
}
public class Customer
{
public customerID;
public customerName;
.....
private ObservableCollection<Order> _orderslist;
public ObservableCollection<Order> orderslist
{get {if (_orderslist == null)
{_orderslist = new ObservableCollection<Order>();}
return _orderslist;
} private set
{_orderslist = value;}}
}
public class MainWindow : Window
{
private static object _syncLockCustomers = new object();
private static object _syncLockOrders = new object();
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var firstCustomer = Customers.customerslist.FirstOrDefault();
custDataGrid.DataContext = Customers.customerslist;
if (firstCustomer != null)
{
custDataGrid.SelectedItem = firstCustomer;
ordersDataGrid.DataContext = firstCustomer.Orders.orderslist;
}
BindingOperations.EnableCollectionSynchronization(Customers.customerslist, _syncLockCustomers);
BindingOperations.EnableCollectionSynchronization(Orders <-what should be here ?, _syncLockOrders);
}
}
考虑一下这个:
// Lock object for synchronization;
private readonly object _syncLock = new object();
/// <summary>
/// Initializes a new instance of MainWindow.
/// </summary>
public MainWindow()
{
InitializeComponent();
// Sync collection with UI
BindingOperations.CollectionRegistering += BindingOperations_CollectionRegistering;
}
/// <summary>
/// Handles the CollectionRegistering event of the BindingOperations control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="CollectionRegisteringEventArgs"/> instance containing the event data.</param>
private void BindingOperations_CollectionRegistering(object sender, CollectionRegisteringEventArgs e)
{
// Ensure collection exists
if (Customers == null || Customers.customerslist == null) return;
// Ensure collection is synched with UI
var myCollection = Customers.customerslist;
if (!Equals(e.Collection, myCollection)) return;
BindingOperations.EnableCollectionSynchronization(myCollection, _syncLock);
}
现在,每次有更新时,集合都会正确同步。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)