将两个可观察集合相互绑定
我有两个 ObservableCollection
类型的属性(在单独的项目中);我想要做的是使用反射和 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
绑定在一起,为什么第一个中的任何更改不会反映在其他中?但同样的事情适用于字符串或双精度类型的属性。
有什么方法可以实现这一点吗?
I have two properties of ObservableCollection<string>
type (in separate projects); What I want to do is to bind these two using reflection and SetBinding
like this -
//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);
This SecondCollProperty
is then bound to a ComboBox's ItemsSource
.
As such this works correctly, values present in firstCollProperty are displayed correctly in combobox; but if some changes are made in firstCollProperty at run time then they are not reflected in ComboBox!(adding new items or creating new collection object).
Changes are reflected correctly after refreshing the binding(again executing the above code).
My question is - If two ObservableCollections
are binded together why any changes in first doesn't get reflected in other? but same thing works for properties of string or double type.
Is there any way of achieving this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只是浏览了一些未解答的老问题并看到了这一点。毫无疑问,您现在已经想出了解决方法,但我的建议是研究 CLinq、Bindable Linq 或 Obtics 之类的东西。有关更多详细信息,请参阅此问题。您将采用第一个集合,针对它创建一个动态查询,并将该动态查询(实现 IObservableCollection)公开为您的第二个属性。
Just going through some old unanswered questions and saw this. Undoubtedly you've come up with a workaround by now, but my recommendation would be look into something like CLinq, Bindable Linq, or Obtics for this. See this question for more details. You'd take the first collection, create a dynamic query against it, and expose that dynamic query (which implements IObservableCollection) as your second property.