CharacterReceived
, кажется, работает для пустых представлений значений (в отличие от TextSubmitted). следующий код отключится, когда пользователь очистит содержимое:
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");
}
}
}
![enter image description here](https://i.stack.imgur.com/Z16Dk.png)
После подтверждения мы можем сделать еще один шаг и сделать некоторые работают над самим предметом и очищают значение.
Решение
Вот мой пример доказательства концепции, которая достигает желаемой цели. Сначала запустите ComboBox в следующем состоянии (пропускает необходимость выбора элемента 1):
<ComboBox IsEditable="True"
CharacterReceived="ComboBox_CharacterReceived"
VerticalAlignment="Center"
HorizontalAlignment="Center"
SelectedIndex="0"
Width="200">
<ComboBoxItem>Item 1</ComboBoxItem>
<ComboBoxItem>Item 2</ComboBoxItem>
</ComboBox>
Обработчик события (комментарии в строке):
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;
}
}
}
}
Часы анимированные GIF результата во время выполнения и вот скриншот
![Final Result](https://i.stack.imgur.com/OyMn8.png)
Надеюсь, это поможет!