WPF Combo Box - 'Cancelling' A Selection Change

By Anoop Madhusudanan

Vote on HN
What if you want to 'cancel' a selection change in a WPF combo box?

Yes, you have an event for handling a selection change, like
ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
But there is no direct way of reverting the SelectedItem to the previous one, if you don't like the change!! Arggggg!!!

Here is one way of tackling this. The parameter e has two collection properties - AddedItems and RemovedItems. The AddedItems contains the items added to the selection, and RemovedItems contains items removed from the selection. As the Combo box supports only one item selected at a given time, always both these collection properties won't have more than one item in in. So, if you want to revert the selection to the previous item, you can do something like
ComboBox combo = (ComboBox)sender;
combo.SelectedItem = e.RemovedItems[0];
But if you do it in SelectionChanged event of the Combo Box, setting the SelectedItem will again trigger the SelectionChanged event, and you'll be in a fix. One simple way is to use a global flag, like this.
  
  private bool handleSelection=true;

  private void ComboBox_SelectionChanged(object sender,
                                        SelectionChangedEventArgs e)
        {
            if (handleSelection)
            {
                MessageBoxResult result = MessageBox.Show
                        ("Continue change?", MessageBoxButton.YesNo);
                if (result == MessageBoxResult.No)
                {
                    ComboBox combo = (ComboBox)sender;
                    handleSelection = false;
                    combo.SelectedItem = e.RemovedItems[0];
                    return;
                }
            }
            handleSelection = true;
        }


Simple problem, but seems that we don't have a better solution :).

2 comments:

  1. Thanks for this Anoop, saved me a bit of time stuffing around :) There's only one potential problem, and that's if the currently selected item is null. When you then try to access the RemovedItems collection you get a null reference exception. So just change your code to:

    if (e.RemovedItems.Count > 0)
    {
    combo.SelectedItem = e.RemovedItems[0];
    }
    else
    {
    combo.SelectedItem = null;
    }

    and it all works fine.

    ReplyDelete
  2. Another solution for issue of recursive calling of event handler without global variable is to cancel handler assignment before programmatic selection change, and reassign it after that.

    ReplyDelete

Please keep your comments clean.

© 2012. All Rights Reserved. Amazedsaint.com