4

我正在尝试仅使用选择的集合对象将 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
4

2 回答 2

4

两种选择:

您可以使用像Bindable LINQ这样的框架,使您的 LINQ 查询返回可观察的集合(因此绑定保持为双向)。

或者,您可以将 ComboBox 的项目绑定到 CollectionViewSource 并通过 Filter 事件处理程序运行每个项目:

<CollectionViewSource
    Source="{Binding MyItems}"
    Filter="OnlyActiveItems"
    x:Key="ItemsView"/>

<ComboBox ItemsSource="{Binding Source={StaticResource ItemsView}}" />

带有代码隐藏:

private void OnlyActiveItems(object sender, FilterEventArgs e)
{
    e.Accepted = false;

    var item = e.Item as Text;
    if (item == null) return;

    e.Accepted = item.Active;
}

请注意,我不完全确定 CollectionViewSource 将识别 INotifyPropertyChanged 接口并在一个元素更改时重新查询列表。如果过滤器方法不起作用,我真的建议 Bindable LINQ。

于 2009-05-17T23:45:25.293 回答
0

CollectionViewSource 类可以向任何 WPF 项控件添加排序和过滤

于 2009-05-18T08:00:19.773 回答