我有一个名为“CompanyView”的 ICollectionVIew
。
我还有一个名为“CompanyFilter”的过滤器。
还有一个绑定(bind)到“SearchCompanyTitle
”属性的Textbox
。
当我在数据绑定(bind)文本框
中输入内容时,“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。显然我做得不对。有什么想法吗?
最佳答案
听起来像是绑定(bind)的完美候选者 Delay
:
<TextBox Text="{Binding SearchCompanyTitle, Delay=1000}"/>
关于c# - 如何不断延迟方法的执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30777182/