Let User Clear ComboBox Selection

The built-in ComboBox for Windows 8 does not come with a way to revert the control back to an unselected state. This is an issue in the scenario where the value in the ComboBox isn’t required an thus needs to be clearable.

A simple solution is to add an extra item to the Combox without any text and a value of -1. We can then wire up the CB with an attached property and handle the SelectionChanged event. Whenever we see a value of -1 being selected we can clear the selection.

One of the pros of clearing the CB is the placeholder text. Upon clearing the selection the placeholder text reappears.

The sample attached property can be seen below


public class ComboBoxHelper : FrameworkElement
{

public static bool GetClearOnEmptyValueSelection(DependencyObject obj)
{
 return (bool)obj.GetValue(ClearOnEmptyValueSelectionProperty);
}

public static void SetClearOnEmptyValueSelection(DependencyObject obj, bool value)
{
 obj.SetValue(ClearOnEmptyValueSelectionProperty, value);
}

public static readonly DependencyProperty ClearOnEmptyValueSelectionProperty =
DependencyProperty.RegisterAttached("ClearOnEmptyValueSelection", typeof(bool), typeof(ComboBoxHelper), new PropertyMetadata(false, (o, args) =>
{
 var cb = (ComboBox)o;

 if ((bool)args.NewValue)
 {
  cb.SelectionChanged += (sender, eventArgs) =>
  {
   if (eventArgs.AddedItems.Count == 1)
   {
    if (cb.SelectedValue == null || string.IsNullOrWhiteSpace(cb.SelectedValue.ToString()) || (cb.SelectedValue is int && (int)cb.SelectedValue == -1))
    {
     cb.SelectedIndex = -1;
    }
   }
 };
}
}));
}

 

With the attached property at hand wiring the CB is as simple as:

<ComboBox ap:ComboBoxHelper.ClearOnSelection="true">

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s