如何不断延迟方法的执行

时间:2015-06-11 09:45:01

标签: c# wpf mvvm

我有ICollectionVIew名为“ CompanyView ”。

我还有一个名为' CompanyFilter '的过滤器。

Textbox绑定到“SearchCompanyTitle”属性。

当我输入数据绑定textbox时,每个字母都会触发“ CompanyFilter ”并过滤“CompanyView”以显示相关结果。

工作正常。

不幸的是,我正在过滤的表格大约有 9 000 行,所以在你按下键盘上的按键并显示在屏幕上之间往往会有明显的延迟。

所以我决定做的是确保在用户输入完成后自动触发过滤器。这提出了ViewModel在用户完成时如何知道的问题?

我所做的是以下内容;

    // This is the property the Textbox is bound to
    private string _searchCompanyTitle = "";
    public string SearchCompanyTitle
    {
        get { return _searchCompanyTitle; }
        set
        {
            _searchCompanyTitle = value;
            OnPropertyChanged("SearchCompanyTitle");

            // After a character has been typed it will fire the below method
            SearchCompany();

        }
    }

    // This method is fired by the above property everytime a character is typed into the textbox
    // What this method is meant to do is wait 1000 microseconds before it fires the filter
    // However I need the timer to be reset every time a character is typed, 
    // Even if it hasn't reached 1000 yet
    // But it doesn't do that. It continues to count before triggering the filter
    private async void SearchCompany()
    {
        bool wait = true;

        while (wait == true)
        {
            await Task.Delay(1000);

            wait = false;
        }

        CompanyView.Filter = CompanyFilter;
    }

    // And this is the filter
    private bool CompanyFilter(object item)
    {
        company company = item as company;

        return company.title.Contains(SearchCompanyTitle);
    }

这就是我的问题。我需要过滤器仅在定时器点击 1000 而不是之前触发时触发。同时,每当该属性触发该方法时,我都需要将计时器返回到0。显然,我做得不对。有什么想法吗?

2 个答案:

答案 0 :(得分:4)

听起来像绑定Delay的完美候选人:

<TextBox Text="{Binding SearchCompanyTitle, Delay=1000}"/>

答案 1 :(得分:0)

一种解决方案可能是使用System.Threading.Timer类。 您可以给它一个回调,以便在经过时间设置时调用。 将过滤方法作为回调并在每次击键时重置计时器的时间。

您可以找到示例here

- 编辑 -

我没有看到你使用WPF,Sinatr的回答是正确的,只是使用绑定延迟<​​/ p>