views:

505

answers:

2

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
+1  A: 

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:

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

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

with code-behind:

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

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

    e.Accepted = item.Active;
}

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.

Matt Hamilton
Yea, I didn't actually try it myself, but I did run across another post somewhere that said that the View will lose the ChangeEvent propagation.However, even if Views did work, I'm thankful for learning about Bindable LINQ. That will sure to be a great help for the future as well.Thanks Matt!
JoshKraker
A: 

The CollectionViewSource class can add sorting and filtering to any WPF items control

Nir