简体   繁体   中英

Delay textChanged Event Xamarin forms

I learning Xamarin, I would like to wait a user to finish to tap on the searchbar then do something. I want to use TextChange to make it dynamic

Here is my Xaml Search code :

 <!--THe search bar-->
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand"  VerticalOptions="FillAndExpand" >
<SearchBar  x:Name="VariableSearchWords"    TextChanged="SearcNews">  </SearchBar>
 </StackLayout>
<!--END THe search bar-->

Here is the function:

   public async void GetNewsData(string title, string Mylanguage)
    {

        newsObj= new List<NewsModel>();
            var client = new NewsSearchClient(new ApiKeyServiceClientCredentials(key));
            var newsResults = client.News.SearchAsync(query: searchTerm, market: Mylanguage, count: 14, originalImage: true).Result;
            if (newsResults.Value.Count > 0)
            {


                for (int i = 0; i < newsResults.Value.Count; i++)
                {
                         var news = new NewsModel();

                        news.NewsUrl = newsResults.Value[i].Url;
                        news.NewsImageUrl = await DownloadImagesAsync(newsResults.Value[i].Image.ContentUrl); 
                        newsObj.Add(news);

                    }



                }

                NewsList.ItemsSource = newsObj;
                // return newsObj;
            }

    }

// search for words

  private async void SearcNews(object sender, TextChangedEventArgs e)
    {

        // StaRT what you want to do after 200 millisecond delay  

        NewsList.ItemsSource = null;

        if (task == null)// very 
        {
            task = Task.Run(async () =>
            {
                await Task.Delay(timeDelay);


               //get data 
               GetNewsData("  ", myuser.NewsLanguage); //getData


                // END what you want to do after 200 millisecond delay
                task = null;
            });
        }                    
    }

Thanks for your help

You could use Task to achieve this effect,check below :

 <SearchBar x:Name="VariableSearchWords" Placeholder="hi" TextChanged="SearcNews"></SearchBar >

 Task task;
 int timeDelay = 1000;
 private async void SearcNews(object sender, TextChangedEventArgs e)
    {
        if (task == null || task.IsCompleted)
        {
            task = Task.Run(async () => 
            {
                await Task.Delay(timeDelay);
                FunctionThatDoesSomethingAfter(VariableSearchWords.Text);// what you want to do after 200 millisecond delay                    
            });
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM