WPF ComboBox delayed filtering

2019-05-23 05:38发布

Consider following situation: there is ComboBox and a filter TextBox, then user types a text in a text box ComboBox items source is updated using filter text. Everything works, but filtering occurs on every typed letter. I want to add a delay before filtering occurs (filter is not applyed while user is typing). What is the simpliest way to do it?

1条回答
我命由我不由天
2楼-- · 2019-05-23 06:24

The most used way of doing this is introducing a timer where everytime the user enters a new character your timespan get's reset but if it is longer than x seconds then execute the code.

Remember to do it async so that if the user starts typing again while you are performing a search you can cancel the async call as that information will now be outdated.

If you are using a viewmodel just change textbox1_TextChanged to the appropriate Properties setter

private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (!tmr.Enabled)
        {
            tmr.Enabled = true;
            tmr.Start();
        }


        TimeSinceType = DateTime.Now;

    }

public DateTime TimeSinceType { get; set; }

protected void Load()
{
      tmr = new Timer();
      tmr.Interval = 200;
      tmr.Elapsed += new ElapsedEventHandler(tmr_Elapsed);
}

void tmr_Elapsed(object sender, ElapsedEventArgs e)
{
    if ((DateTime.Now - TimeSinceType).Seconds > .5)
    {
        Dispatcher.BeginInvoke((Action)delegate()
        {
            //LoadData();
            tmr.Stop();
        });
    }
}
查看更多
登录 后发表回答