Reputation: 297
I have a ComboBox which is binded with a List. Consider I have 10 Items in the List, so in the combobox also.
Currently 2nd Item is selected in the ComboBox.
Now I am selecting the 3rd item in the ComboBox.
In the Combobox SelectionChanged event, I am doing some validation and validation fails so I don want my Selection is changed from 2nd item to 3rd item or the selection should remain in 2nd item.
Please let me know how to do this?
In the ComboBox SelectionChanged event, I tried to set ComboBox.SelectedItem = 2ndItem.
But this didn't work properly.
Hope, my requirement is clear. If you have any doubt then please feel free to ask me.
regards,
Vimal
Upvotes: 0
Views: 3436
Reputation: 36775
Disable the item so that the user sees that they are currently not an option (and also can not select). You can set the IsEnabled-property on the ComboBoxItem.
If you work with MVVM, add an IsEnabled-property to your ViewModel and bind it on the IsEnabled-property of the container (ItemContainerStyle
).
The best option IMO would however be, not to show the items that are not selectable.
Update
As promised in a comment, here the Dispatcher-Code to set the SelectedItem delayed:
Dispatcher.BeginInvoke(new Action(delegate {
yourComboBox.SelectedItem=yourOldItem;
}), System.Windows.Threading.DispatcherPriority.ContextIdle, null);
I think this will help, however it's not very nice. If you have the possibility to disable or hide the items, this would be much better. BTW, I took ContextIdle for the dispatcher-priority. This is a very strong value. You can play around which value fits to your needs.
CoerceValueCallback
Another possibility would be to derive from Combobox
, change the metadata for the SelectedItem and add a CoerceValueCallback
to it. There in, you can reset the value.
Upvotes: 1