Hello every one in the WPF application I have the following event handler for PreviewTextInput event in ComboBox control.
private void OnTextComboBoxPreviewTextInput(object sender, TextCompositionEventArgs e)
{
var comboBox = sender as ComboBox;
if (!comboBox.IsDropDownOpen)
{
return;
}
if (!comboBox.IsEditable || !comboBox.IsReadOnly)
{
return;
}
foreach (var item in comboBox.Items)
{
if (item == null)
{
continue;
}
var textSearch = TextSearch.GetTextPath(comboBox);
var stringItem = item as string;
if (stringItem != null)
{
if (stringItem.StartsWith(e.Text, StringComparison.InvariantCultureIgnoreCase))
{
SelectItemInComboBox(comboBox, item);
break;
}
continue;
}
var dependencyObjItem = item as DependencyObject;
if (dependencyObjItem != null)
{
var textMember = TextSearch.GetText(dependencyObjItem);
if (!string.IsNullOrEmpty(textMember))
{
var selectorFunc = ExpressionHelper.GetMemberFunction(dependencyObjItem, textMember);
var textValue = selectorFunc(dependencyObjItem);
if (textValue.ToString().StartsWith(e.Text, StringComparison.InvariantCultureIgnoreCase))
{
SelectItemInComboBox(comboBox, item);
break;
}
continue;
}
}
if (!string.IsNullOrEmpty(textSearch))
{
var selectorFunc = ExpressionHelper.GetMemberFunction(item, textSearch);
var textValue = selectorFunc(item);
if (textValue.ToString().StartsWith(e.Text, StringComparison.InvariantCultureIgnoreCase))
{
SelectItemInComboBox(comboBox, item);
break;
}
}
}
e.Handled = true;
}
private void SelectItemInComboBox(ComboBox comboBox, object item)
{
var comboBoxItem = comboBox.ItemContainerGenerator.ContainerFromItem(item) as ComboBoxItem;
comboBoxItem.IsSelected = true;
}
The main purpose of this code is to select an item in ComboBox via pressing letter key. in this code there are duplication logic. Help me please to refactor this code for remove duplication. Thanks in advance.