将两个可观察的集合彼此绑定

问题描述 投票:4回答:1

我有ObservableCollection<string>类型的两个属性(在单独的项目中);我想做的是使用反射和SetBinding像这样绑定这两个-

//Get the PropertyDescriptor for first collection property
PropertyDescriptor relatedPropertyDesc = prop.Find(firstCollPropName, false);
Binding relatedPropBinding = new Binding(relatedPropertyDesc.Name);
relatedPropBinding.Source = this.SelectedItem;
relatedPropBinding.Mode = BindingMode.TwoWay;
//Bind the second collection property using binding created above
propItem.SetBinding(MyItem.SecondCollProperty, relatedPropBinding);

然后将此SecondCollProperty绑定到ComboBox的ItemsSource

这样可以正常工作,firstCollProperty中存在的值会在组合框中正确显示;但是如果在运行时对firstCollProperty进行了某些更改,则它们不会反映在ComboBox中!(添加新项或创建新的集合对象)。

在刷新绑定后(正确执行上述代码),更改可以正确反映。

我的问题是-如果将两个ObservableCollections绑定在一起,为什么对first所做的任何更改都不会反映在其他内容中?但相同的东西对于string或double类型的属性也有效。

有什么方法可以实现?

wpf silverlight data-binding reflection observablecollection
1个回答
0
投票

只需经历一些未解决的老问题,就可以看到。无疑,您现在已经提出了解决方法,但是我的建议是为此考虑使用CLinq,Bindable Linq或Obtics之类的东西。有关更多详细信息,请参见this question。您将选择第一个集合,对其进行动态查询,然后将该动态查询(实现IObservableCollection)公开为第二个属性。

© www.soinside.com 2019 - 2024. All rights reserved.