views:

340

answers:

1

I have a ComboBox in a WPF application that is bound to an ObservableCollection of Department objects in a C# ViewModel class. I want to use the combo box to filter another collection by department (And indeed it works for that now) The problem is that I want to add an additional option "All" to the top of the list. Is there a correct way to do this. Making a fake department feels wrong in so many ways.

The ComboBox

<ComboBox ItemsSource="{Binding Path=Departments}" 
          SelectedValue="{Binding Path=DepartmentToShow , Mode=TwoWay}" />
+5  A: 

You could use a CompositeCollection as the ItemsSource for the ComboBox to include the "All" option. You need to set the Collection property of the CollectionContainer to your "ObservableCollection of Department objects".

<ComboBox >
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <ComboBoxItem>All</ComboBoxItem>
            <CollectionContainer x:Name="departmentCollection"/>
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>

Not sure if this will be suitable for your filtering situation however...

Simon Fox
+1 Wow as an experienced WPF programmer I was not even aware of `CompositeCollection`! There are all sorts of workarounds for this when searching the internet, but none mention this! Incredible...
Aviad P.
Yeah when i read this i was amazed. I have been doing some looking into it this morning and i think it will do the trick. Right now the filtering is done in the building of the Linq query so I am thinking I can test for 'All' and if that is not selected iterate the peopleCollection. In the future I was planning on refactoring and using a CollectionViewSource to filter the view without requerying; I'm not sure how that would work but for this question I have my answer. Thank You!
Mike B
@Aviad yes it is a nice solution, one thing that does suck a bit is that you can't bind to the Collection property via DataContext as CompositeCollection is not Freezable. This can be worked around by binding to a static resource...
Simon Fox
the solution to this question has a an example of how to bind in this manner http://stackoverflow.com/questions/1189052/why-is-compositecollection-not-freezable not particularly pretty IMO but does the trick...
Simon Fox