So I've got an object that has an observable collection. Most places I bind to this collection I only want the user to select a single item. But in one place I want the combobox to include an all items option.
Is the way to do this simply with xaml converter?
It seems like doing it in the view model would be a good idea, but it's really a lot dependency object goop to basically wire up an collection that is two objects deep for an on change event, where as the xaml converter just works.
But I always feel like xaml converters should be generic and reusable, where in this instance, the xaml converter would be more of a one off.
Of course the third option would be to create one off list for UI in the object that contains the standard observable collection. But this seems to be mixing the logic and presentation in a way that 开发者_StackOverflowmakes me uncomfortable.
Take a look at CompositeCollection. It lets you concatenate multiple collections into a single collection -- sort of the XAML equivalent of the LINQ Concat. It implements INotifyCollectionChanged, so it should be able to react to changes if some of its inner collections are ObservableCollections.
CompositeCollection also lets you add individual elements, so you wouldn't even need to wrap your "All Items" in a collection of its own. (Instead, you have to wrap collections in a CollectionContainer. See the examples on the CompositeCollection doc page.)
I had a similar need, and ended up using the solution discussed in this article: How To Select Null/None in a ComboBox/ListBox/ListView.
You can replace the "(None)" string on line 98 with "All" or something similar. Then just add logic in your ViewModel to treat a null value as "All" in whatever manner is appropriate. It's a little annoying to have an extra class lying around but it makes the code a lot cleaner if you do need this in several places.
精彩评论