First you need a handler for your normal TextChanged
event handler for the TextBox
:
private bool InProg;
internal void TBTextChanged(object sender, TextChangedEventArgs e)
{
var change = e.Changes.FirstOrDefault();
if ( !InProg )
{
InProg = true;
var culture = new CultureInfo(CultureInfo.CurrentCulture.Name);
var source = ( (TextBox)sender );
if ( ( ( change.AddedLength - change.RemovedLength ) > 0 || source.Text.Length > 0 ) && !DelKeyPressed )
{
if ( Files.Where(x => x.IndexOf(source.Text, StringComparison.CurrentCultureIgnoreCase) == 0 ).Count() > 0 )
{
var _appendtxt = Files.FirstOrDefault(ap => ( culture.CompareInfo.IndexOf(ap, source.Text, CompareOptions.IgnoreCase) == 0 ));
_appendtxt = _appendtxt.Remove(0, change.Offset + 1);
source.Text += _appendtxt;
source.SelectionStart = change.Offset + 1;
source.SelectionLength = source.Text.Length;
}
}
InProg = false;
}
}
Then make a simple PreviewKeyDown
handler:
private static bool DelKeyPressed;
internal static void DelPressed(object sender, KeyEventArgs e)
{ if ( e.Key == Key.Back ) { DelKeyPressed = true; } else { DelKeyPressed = false; } }
In this example "Files" is a list of directory names created on application startup.
Then just attach the handlers:
public class YourClass
{
public YourClass()
{
YourTextbox.PreviewKeyDown += DelPressed;
YourTextbox.TextChanged += TBTextChanged;
}
}
With this whatever you choose to put in the List
will be used for the autocomplete box. This may not be a great option if you expect to have an enormous list for the autocomplete but in my app it only ever sees 20-50 items so it cycles through very quick.