AutoComplete TextBox in WPF

后端 未结 8 1444
忘了有多久
忘了有多久 2020-11-27 11:17

Is it possible to make a textbox autocomplete in WPF?

I found a sample where a combo box is used and the triangle is removed by editing the style template.

8条回答
  •  日久生厌
    2020-11-27 11:38

    I know this is a very old question but I want to add an answer I have come up with.

    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.

提交回复
热议问题