C# wait for user to finish typing in a Text Box

前端 未结 15 1220
无人及你
无人及你 2020-11-27 18:16

Is there a way in C# to wait till the user finished typing in a textbox before taking in values they have typed without hitting enter?

Revised this question a little

相关标签:
15条回答
  • 2020-11-27 18:40

    In UWP, I did a delayed check by making a static lastTimeOfTyping and checking the time when the "TextChanged" event happened. This waits till the static lastTimeOfTyping matches when a new "TextChanged" time matches and then executes the desired function.

        private const int millisecondsToWait = 500;
        private static DateTime s_lastTimeOfTyping;
        private void SearchField_OnTextChanged(object sender, TextChangedEventArgs e)
        {
            var latestTimeOfTyping = DateTime.Now;
            var text = ((TextBox)sender).Text;
            Task.Run(()=>DelayedCheck(latestTimeOfTyping, text));
            s_lastTimeOfTyping = latestTimeOfTyping;
        }
    
        private async Task DelayedCheck(DateTime latestTimeOfTyping, string text)
        {
            await Task.Delay(millisecondsToWait);
            if (latestTimeOfTyping.Equals(s_lastTimeOfTyping))
            {
                // Execute your function here after last text change
                // Will need to bring back to the UI if doing UI changes
            }
        }
    
    0 讨论(0)
  • 2020-11-27 18:43

    If you are using WPF and .NET 4.5 or later there is a new property on the Binding part of a control named "Delay". It defines a timespan after which the source is updated.

    <TextBox Text="{Binding Name, Delay=500}" />
    

    This means the source is updated only after 500 milliseconds. As far as I see it it does the update after typing in the TextBox ended. Btw. this property can be usefull in other scenarios as well, eg. ListBox etc.

    0 讨论(0)
  • 2020-11-27 18:43

    As an asynchronous extension method. Adapted from Grecon14's answer.

    public static class UIExtensionMethods
    {
        public static async Task<bool> GetIdle(this TextBox txb)
        {
            string txt = txb.Text;
            await Task.Delay(500);
            return txt == txb.Text;
        }
    }
    

    Usage:

    if (await myTextBox.GetIdle()){
        // typing has stopped, do stuff
    }
    
    0 讨论(0)
提交回复
热议问题