VS中使用c#的WPF应用程序。我继承ComboBox,将其命名为AutoCompleteComboBox。我需要IsEditable True,做到了。当我在AutoCompleteComboBox(Control)中写入时,每个字符都被添加到字符串的末尾。我无法通过开始键入来删除突出显示,并且我的光标始终位于第一个索引处。 (简而言之,我需要帮助来动态创建"可编辑"属性)
class AutoCompleteComboBox : ComboBox
{
/// <summary>
/// The value of selected items, this is used since what is shown in the TextBox
/// can be different than what is to be stored in the database.
/// </summary>
public string Value;
/// <summary>
/// The original data context of the Dropdown.
/// </summary>
private object _originalDataContext;
public AutoCompleteComboBox() : base()
{
this.IsEditable = true;
this.StaysOpenOnEdit = true;
this.IsTextSearchEnabled = false;
this.KeyDown += filterItems;
}
private void filterItems(object sender, KeyEventArgs e)
{
if (this.Text.Length > 0)
{
this.IsDropDownOpen = true;
}
if (_originalDataContext == null)
{
_originalDataContext = this.DataContext;
}
// Need to implement exception handling.
AutoCompleteComboBox cb = (AutoCompleteComboBox)sender;
string filterCriteria = cb.Text.ToUpper();
// Whatever the display member path is, that is our search criteria.
string displayMemberPath = cb.DisplayMemberPath;
// Datatable with the original goods.
DataTable table = (DataTable)_originalDataContext;
try
{
// Remove any null entries from the table
DataTable tableWithoutNulls = table.AsEnumerable()
.Where(i => i.Field<String>(displayMemberPath) != null).CopyToDataTable();
// Get the entries that match what the user typed in
DataTable revisedTable = tableWithoutNulls.AsEnumerable()
.Where(i => i.Field<String>(displayMemberPath).ToUpper().Contains(filterCriteria)).CopyToDataTable();
// Set the data context of the control to the new results
this.DataContext = revisedTable;
}
catch (InvalidOperationException)
{
// No matches were found. Set the datacontext to blank.
this.DataContext = new DataTable();
}
catch (ArgumentNullException)
{
// No matches were found. Set the datacontext to blank.
this.DataContext = new DataTable();
}
}
}