我已經搜索了整個互聯網尋找解決方案沒有結果。 在我的程序中,我有UI線程顯示在兩個DataGrids Customers和Orders中。訂單顯示給選定的客戶。收藏的定義及其更新發生在後臺。 UI目的只是爲了顯示最新的信息。我利用了C#4.5中引入的最新功能:BindingOperations.EnableCollectionSynchronization方法。 在我的程序中,我有定義客戶類集合的類客戶。反過來,Customer類定義了Order類的集合。我的問題是我不知道如何正確編碼下面的代碼的最後一行,它涉及到Order集合綁定同步。這段代碼被簡化了,我省略了OnPropertyChange代碼行,以確保在數據網格中顯示正確的屬性 - 我想關注集合。C#如何編碼集合的EnableCollectionSynchronization
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);
}
}
如何在非UI類中添加BindingOperations.EnableCollectionSynchronization?它返回一個錯誤,說「BindingOperations在當前上下文中不存在」 – Zibi
System.Windows.Data命名空間的BindingOperations類部分,因此您需要對PresentationFramework.dll的引用。 – WasGoodDone
它似乎沒有工作。讓我/以前的解決方案到位,我可以看到所有客戶的名單 - 現在,他們也不可見。還有其他解決方案嗎?我還希望分離UI和操作/數據層。 – Zibi