将两个 Observable 集合相互绑定

akj*_*shi 6 data-binding reflection silverlight wpf observablecollection

我有两个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);
Run Code Online (Sandbox Code Playgroud)

SecondCollProperty是然后绑定到一个ComboBox的ItemsSource

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

刷新绑定(再次执行上面的代码)后,更改会正确反映。

我的问题是 -如果将两个ObservableCollections绑定在一起,为什么第一个中的任何更改不会反映在其他中?但同样的事情适用于 string 或 double 类型的属性。

有没有办法实现这一目标?

Ken*_*ith 1

只是浏览了一些未解答的老问题并看到了这一点。毫无疑问,您现在已经想出了解决方法,但我的建议是研究 CLinq、Bindable Linq 或 Obtics 之类的东西。请参阅此问题了解更多详细信息。您将采用第一个集合,针对它创建一个动态查询,并将该动态查询(实现 IObservableCollection)公开为您的第二个属性。