WPF 仅使用集合项目的子集绑定到组合
我正在尝试仅使用集合对象的选择来将 TwoWay 绑定设置到组合框。 目前,如果我只想绑定集合中的所有内容,则一切正常,但在下面的示例类中,如果我只想显示 Active=True 的项目怎么办? 我可以使用 LINQ 过滤项目,例如 ItemsSource = FROM x IN Coll WHERE x.Active=True 但随后我丢失了 TwoWay 绑定。 即,如果源中的名称或活动状态是从其他地方更新的,则组合框不会自动更新。
有可能做到吗? 如果没有,有处理过这个问题的人有一些建议吗?
'The Class
Public Class Test
Implements ComponentModel.INotifyPropertyChanged
Private _Name As String
Private _Active As Boolean
Public Sub New(Name As String, Active As Boolean)
_Name=Name
_Active=Active
End Sub
Public Property Name() As String
End Class
'Declare a Collection and add some Tests, then bind to Cbo in Page Load
Dim Coll As New ObservableCollection
Coll.Add(New Test("Test1", True))
Coll.Add(New Test("Test2", False))
Coll.Add(New Test("Test3", True))
TheComboBox.ItemsSource=Coll
I'm trying to set a TwoWay binding to a combo box using only a selection of a collection's objects. Currently, everything works out ok if I just want to bind everything in the colelction, but in the example class below, what if I only want to show items where Active=True? I can filter the items using LINQ like ItemsSource = FROM x IN Coll WHERE x.Active=True but then I lose the TwoWay binding. Ie, if the name or the active state in the source is updated from elsewhere, the combo box does not automatically update.
Is the possible to do? If not, does anyone who has had to deal with this have some suggestions?
'The Class
Public Class Test
Implements ComponentModel.INotifyPropertyChanged
Private _Name As String
Private _Active As Boolean
Public Sub New(Name As String, Active As Boolean)
_Name=Name
_Active=Active
End Sub
Public Property Name() As String
End Class
'Declare a Collection and add some Tests, then bind to Cbo in Page Load
Dim Coll As New ObservableCollection
Coll.Add(New Test("Test1", True))
Coll.Add(New Test("Test2", False))
Coll.Add(New Test("Test3", True))
TheComboBox.ItemsSource=Coll
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
两个选项:
您可以使用像 Bindable LINQ 这样的框架,使您的 LINQ 查询返回可观察的集合(因此绑定保持不变)作为双向)。
或者,您可以将 ComboBox 的项目绑定到 CollectionViewSource 并通过 Filter 事件处理程序运行每个项目:
使用隐藏代码:
请注意,我不完全确定 CollectionViewSource 是否会识别 INotifyPropertyChanged 接口并在一个元素出现时重新查询列表变化。 如果过滤器方法不起作用,我真的建议使用 Bindable LINQ。
Two options:
You can use a framework like Bindable LINQ that makes your LINQ queries return observable collections (thus the binding stays as two-way).
Or you could bind your ComboBox's items to a CollectionViewSource and run each item through a Filter event handler:
with code-behind:
Note that I'm not entirely sure that a CollectionViewSource will recognise the INotifyPropertyChanged interface and re-query the list when one element changes. I'd really suggest Bindable LINQ if the filter approach doesn't work.
CollectionViewSource 类可以向任何 WPF 项目控件添加排序和过滤功能
The CollectionViewSource class can add sorting and filtering to any WPF items control