I'm looking for a way to allow users to enter an empty string, or clear the value of an editable ComboBox in my UWP app. Seems simple enough, but I have not had any luck so far.
Here is the simplest code to reproduce the problem. Place the following control in your test application:
<ComboBox IsEditable="True">
<ComboBoxItem>Item 1</ComboBoxItem>
</ComboBox>
Expected: The ComboBox would accept an empty string and leave the text cleared.
Actual: The text reverts to the previously selected item's text.
Additional notes:
Any thoughts on how to make this work?
CharacterReceived seems to work for empty value submissions (as opposed to TextSubmitted). the following code will whittle out when the user clears the contents:
private void ComboBox_CharacterReceived(UIElement sender, CharacterReceivedRoutedEventArgs args)
{
if (sender is ComboBox cb)
{
Debug.WriteLine($"Char Received: {args.Character}");
if (args.Character == 8 && string.IsNullOrEmpty(cb.Text))
{
Debug.WriteLine("ComboBox Cleared");
}
}
}

With that confirmed, we can take it a step further and do some work on the item itself and clear the value.
Solution
Here's my proof of concept example that achieves your requested goal. First start with the ComboBox in the following state (skips the need to select Item 1):
<ComboBox IsEditable="True"
CharacterReceived="ComboBox_CharacterReceived"
VerticalAlignment="Center"
HorizontalAlignment="Center"
SelectedIndex="0"
Width="200">
<ComboBoxItem>Item 1</ComboBoxItem>
<ComboBoxItem>Item 2</ComboBoxItem>
</ComboBox>
The event handler (comments inline):
private void ComboBox_CharacterReceived(UIElement sender, CharacterReceivedRoutedEventArgs args)
{
if (sender is ComboBox cb)
{
Debug.WriteLine($"Char Received: {args.Character}");
// If the ComboBox was cleared
if (string.IsNullOrEmpty(cb.Text))
{
Debug.WriteLine("ComboBox Cleared");
// Get a reference to the currently editing item (aka "Item 1"
var item = cb.Items?.FirstOrDefault();
// Cast it safely with pattern match
if(item is ComboBoxItem currentItem)
{
// TAKEAWAY - Clear the content of the item with an empty string
currentItem.Content = "";
// Unselect the item
cb.SelectedIndex = -1;
}
}
}
}
Watch animated GIF of the result at runtime and here's a screenshot

I hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With