views:

116

answers:

3

I am working on a wpf application, when using Combo Box control i am assigning ItemsSource to it. So, it displays a list of items with no item selected, now user can select an item of his choice. When user has made a selection he has no option to undo that. I want him to be able to get the initial state where no item is selected. How can i do that?

+1  A: 

There are multiple ways that would also be similar in windows forms programming. You could do either of the following:

1) Add a blank or --None-- record to your combobox datasource that is the default record. 2) You could monitor the keypress event and say use the ESC key to reset the selected index back to -1.
3) If your combobox allows typing you could also allow them to clear the text and onleave if the text field is blank set the selectedindex back to -1 so that it does not get reset to the selected value.

Alot of the time my users prefer option 1 but that's my users.

That should give you some options.

Joshua Cauble
i have used the first way earlier but in that case suppose my ComboBox has a List of People type assigned to its ItemsSource, and set DisplayMemberPath to Name property of People type. then i need to Add an people object in the List with Name="No Select". Isn't there a way that i can have item named 'No Select' directly in the ComboBox as well as my other People objects.
viky
I did find this link http://www.blueedge.nl/weblog/post/Nullable-ComboBox-in-Silverlight.aspx which does what you are asking. Might be a little much but it does the same thing as number 1 without having to manually add blank records. The solution looks like it should work out well. LOL, I might even adapt it for my own needs. Other than that I have to agree with a lot of people on the web taht there just is not much out there other than adding a dummy record to achieve what you are looking for. So other than that I'd suggest one of the keypress / text monitoring solutions.
Joshua Cauble
A: 

I'd go for resetting back to a --None-- record over the default blank record (with an index of -1) every time. If you're handling events for "selection changed" or something on the ComboBox then you risk getting null-reference errors if you point the box at -1, and it's just as easy since the only change you'd have to make is set the selected index to (say) 0 rather than -1.

myComboBox.SelectedIndex = 0; //where 0 is a given default content entry.
MoominTroll
A: 

Generally speaking, I find that if I need to add complexity to a WPF application, adding it to the data source is more robust than adding it to the XAML.

In your example, I'd fix this in my data source. If I have:

public IEnumerable<Person> People { get {...} }

in my data source, I'd add this:

public IEnumerable<Person> PeopleWithNull
{
   get
   {
      return (new List<Person> { null }).Concat(People);
   }
}
Robert Rossney