开发者

WPF ComboBox delayed filtering

Consider following situation: there is ComboBox and a filter TextBox, then user types a text in a text box ComboBox it开发者_如何学编程ems 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?


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();
        });
    }
}


This can be done much easier now by putting a delay directly on the binding:

<ComboBox Text={Binding MyBinding, Delay=200} />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜