WPF ComboBox延迟过滤

Pet*_*lin 2 c# wpf asynchronous filter

考虑以下情况:有ComboBox和过滤器TextBox,然后用户在文本框中键入文本ComboBox项目源使用过滤器文本更新.一切正常,但每个打字的字母都会进行过滤.我希望在过滤发生之前添加延迟(在用户键入时不应用过滤器).最简单的方法是什么?

TBo*_*jnr 6

最常用的方法是引入一个计时器,每当用户输入一个新字符时,你的时间跨度就会被重置,但如果它长于x秒,则执行代码.

请记住执行异步操作,以便在执行搜索时用户再次开始键入时,您可以取消异步调用,因为该信息现在将过时.

如果您使用的是viewmodel,只需将textbox1_TextChanged更改为相应的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();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)