"All" value for a Combobox Data Filter in WPF
During the construction of user control I populate the combobox with some data. Works fine. I have Status.ID as valuePath and Status.Name as displayPath.
cmb.ItemsSource = dbEntities.Status
The comobox will be used as a filter control and I need to insert some value for "All", which will be used as the empty filter.
First I tried a funny solution:
ObjectSet objectSet= dbEntities.Status;
Status stAll = new Status();
stAll.ID = -1;
stAll.Name = "All";
objectSet.AddObject(stAll);
cmb.ItemsSource = objectSet;
For some reason the object is not added to the objectSet. It didnt throw any exception either.
Then I tried to insert it manually to the first index but I got the error: "Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead." My code looked like:
cmb.ItemsSource = entities.Status;
cmb.Items.Insert(0,"All");
Both didnt work. What would be the easiest way to add that line to the combobox? The error message got me confused. I am not sure how to use the ItemsSource for such a purpose.
edit: I did not have enough rep to answer my own question so here is the working code. Thanks Craig again.
CompositeCollection comp = new CompositeCollection();
comp.Add(new CollectionContainer {Collectio开发者_JAVA百科n = dbEntities.Status});
Status stAll = new Status();
stAll.ID = -1;
stAll.Name = "All";
comp.add(stAll);
cmb.ItemsSource = comp;
//do whatever filter you want when the selected value is -1
There are a couple different problems with what you are trying to do. You can't manipulate the Items
when you are using the ItemsSource
, instead you have to go through the object that is set to the ItemsSource
. That is what the error message is about in the second part. Its because when you set the ItemsSource
the Items
value is unused it is not populated with the values of the ItemsSource
.
I'm not familiar enough with the ObjectSet
class to know why the first case is not working. However, it seems awkward to add an item to your values you are pulling from somewhere else, just to have the all case. The better solution is to use a null value to represent nothing. Unfortunately, there is no built in way to do this in WPF. However, there is a fairly easy solution of using an Adaptor do do this. I have used this solution a NullItemSelectorAdaptor, that enables null as a selection even if null is not in the list. All you have to do is wrap your combobox in the NullItemSelectorAdapter
and null will be added as a value. The blog post explains everything pretty clearly, so I won't repeat it. You than can setup your filter so that null equates to no filtering.
精彩评论