C# 使用从JSON数据在listview上更改的文本框显示搜索结果

C# 使用从JSON数据在listview上更改的文本框显示搜索结果,c#,json,listview,uwp,C#,Json,Listview,Uwp,我有一个文本框,可以使用文本框和列表视图进行搜索。当用户键入字母o时,它将在listview上显示字母o的搜索结果;当用户键入单词omapukis时,它将显示单词omapukis的搜索结果 XAML: 代码: 我有一个问题,当键入字母o时,它会在listview上显示字母o的搜索结果,而当用户键入omapukis时,则会显示搜索结果,并显示来自o、om、oma、omapukis。我想显示单词omapukis的搜索结果,仅显示最后一个字母或单词的搜索结果。 然后我搜索单词kalingga,然后搜索

我有一个文本框,可以使用文本框和列表视图进行搜索。当用户键入字母o时,它将在listview上显示字母o的搜索结果;当用户键入单词omapukis时,它将显示单词omapukis的搜索结果

XAML:

代码:

我有一个问题,当键入字母o时,它会在listview上显示字母o的搜索结果,而当用户键入omapukis时,则会显示搜索结果,并显示来自o、om、oma、omapukis。我想显示单词omapukis的搜索结果,仅显示最后一个字母或单词的搜索结果。 然后我搜索单词kalingga,然后搜索结果会出现在om,oma,oma,omapukis,ka,kali,kalingga。我想显示单词kalingga的搜索结果,只显示最后一个字母或单词的搜索结果


如何解决此问题,以便在listview中仅显示用户输入的最后一个字母或单词的搜索结果?

在搜索数据之前,您可以稍等片刻。尝试在TextChanging方法add\u lockable as private field of type object的开头添加此代码段:


这将在用户输入文本后等待四分之一秒,然后开始搜索。如果术语发生更改,它将只搜索新术语。尝试使用延迟时间来找到适合您的场景的最佳时间。

您应该使用AutoSuggestBox:并使用TaskCancellation进行上一次搜索。基本上,如果用户修改了AutoSuggestBox上的任何内容,则可以取消以前的搜索。像这样的

private CancellationTokenSource CTS = new CancellationTokenSource();

public async Task StartSearch(string query)
    {
        this.CTS.Cancel(true);
        this.CTS = new CancellationTokenSource();

        try
        {
            await Task.Run(() =>
            {
                try
                {
                    if (this.CTS.IsCancellationRequested)
                    {
                        return;
                    }

                    // Your actual searching logic... If you decide to update the UI here then make sure this runs on UI Thread.

                    if (this.CTS.IsCancellationRequested)
                    {
                        return;
                    }
                }
                catch (Exception ex)
                {
                   // Logger...
                }
            }, this.CTS.Token);
        }
        catch (TaskCanceledException taskCnclErr)
        {
            // You can ignore this error
        }
        catch (Exception ex)
        {
            //Logger...
            throw;
        }
        finally
        {

        }
    }
现在,将StartSearch方法挂接到AutoSuggestBox中的事件触发器
text已更改或已提交查询

是否使用UWP?或者WPF?@saurabh我正在使用UWPOr,你也可以通过文本框上的TextChange事件来做同样的事情,以防你不想使用新控件。我遇到了一个类似于下图的错误:我使用的代码是,错误似乎是在非UI线程上执行UI操作。尝试删除Task.Runsaurabh:如果我删除Tak.Run,它将无法显示用户键入的字母或单词的搜索结果。如何解决这个问题?我遇到了一个类似下图的错误:@Rose-您必须初始化字段。在ctor中,添加_lockable=新对象;我已声明“可锁定到私人对象”可锁定;但出现的错误消息与前一条评论中给出的消息类似
ObservableCollection<SearchClass> suggestionDatasourceDetail = new ObservableCollection<SearchClass>();
ObservableCollection<SearchClass> historyDatasourceDetail = new ObservableCollection<SearchClass>();
private async void searchBox_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
    string keyword = searchBox.Text;
    suggestionList.ItemsSource = null;
    suggestionList.Items.Clear();
    suggestionDatasourceDetail.Clear();
    koneksiErrorStack.Visibility = Visibility.Collapsed;
    requestErrorStack.Visibility = Visibility.Collapsed;

    ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
    if (connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess)
    {
        itemGridView.Visibility = Visibility.Visible;
        busyIndicator.IsActive = true;

        try
        {
            string urlPath = "http://.../suggest.json?q=" + keyword + "&module=listings&page=1&token=3f63-dc43-c8d5-eb45-8cbf-b72d-9d98-800f";
            var httpClient = new HttpClient(new HttpClientHandler());

            var values = new List<KeyValuePair<string, string>>{};

            HttpResponseMessage response = await httpClient.GetAsync(urlPath);
            response.EnsureSuccessStatusCode();

            if (!response.IsSuccessStatusCode)
            {
                busyIndicator.IsActive = false;
                RequestException();
            }

            string jsonText = await response.Content.ReadAsStringAsync();
            JsonObject jsonObject = JsonObject.Parse(jsonText);
            JsonArray jsonData = jsonObject["data"].GetArray();

            foreach (JsonValue groupValue1 in jsonData)
            {
                JsonObject groupObject2 = groupValue1.GetObject();

                double id = groupObject2["id"].GetNumber();
                string title = groupObject2["title"].GetString();
                string type = groupObject2.ContainsKey("type") && groupObject2["type"] != null ? groupObject2["type"].GetString() : string.Empty;

                SearchClass file1 = new SearchClass();
                file1.ID = Convert.ToInt32(id);
                file1.Title = title;

                if (type != string.Empty)
                {
                    file1.Type = type;
                }
                if (file1.Type != "blog")
                {
                    suggestionDatasourceDetail.Add(file1);
                }
            }
            suggestionList.ItemsSource = searchDatasourceDetail;

            if (suggestionDatasourceDetail.Count == 0)
            {
                busyIndicator.IsActive = false;
                loading.Visibility = Visibility.Collapsed;
                suggestionList.Visibility = Visibility.Collapsed;
            }

            else
            {
                busyIndicator.IsActive = false;
                loading.Visibility = Visibility.Collapsed;
                suggestionList.Visibility = Visibility.Visible;
            }
        }
        catch (HttpRequestException ex)
        {
            busyIndicator.IsActive = false;
            loading.Visibility = Visibility.Collapsed;
            RequestException();
            suggestionList.Visibility = Visibility.Collapsed;
        }
    }
    else
    {
        busyIndicator.IsActive = false;
        loading.Visibility = Visibility.Collapsed;
        ConnectionException();
        suggestionList.Visibility = Visibility.Collapsed;
    }
}
lock (_lockable)
{
    var term = searchBox.Text;

    await Task.Delay(250);

    if (term != searchBox.Text)
        return;
}
private CancellationTokenSource CTS = new CancellationTokenSource();

public async Task StartSearch(string query)
    {
        this.CTS.Cancel(true);
        this.CTS = new CancellationTokenSource();

        try
        {
            await Task.Run(() =>
            {
                try
                {
                    if (this.CTS.IsCancellationRequested)
                    {
                        return;
                    }

                    // Your actual searching logic... If you decide to update the UI here then make sure this runs on UI Thread.

                    if (this.CTS.IsCancellationRequested)
                    {
                        return;
                    }
                }
                catch (Exception ex)
                {
                   // Logger...
                }
            }, this.CTS.Token);
        }
        catch (TaskCanceledException taskCnclErr)
        {
            // You can ignore this error
        }
        catch (Exception ex)
        {
            //Logger...
            throw;
        }
        finally
        {

        }
    }