我从服务器得到响应,它是 Json,其中有关于街道名称的数据。然后我将响应字符串解析为 Json,并将街道名称添加到列表中。我希望此列表显示为自动完成框中的下拉列表,当文本长度等于两个时(我在自动完成框中按第二个字符)。我也使用 Json.Net 库。我使用这段代码:
这是我使用的类(JsonWorker):
class JsonWorker
{
public async Task<HttpWebResponse> send(string requestUrl, JObject jsonObjesct)
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(requestUrl);
request.ContentType = "text/plain; charset=utf-8";
request.Method = "POST";
byte[] jsonAsBytes = Encoding.UTF8.GetBytes(jsonObjesct.ToString());
Stream x = await request.GetRequestStreamAsync();
await x.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
x.Close();
HttpWebResponse response = (HttpWebResponse) (await request.GetResponseAsync());
return response;
}
public async Task<string> get(
HttpWebResponse response)
{
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
string str_responsefromjson = await sr.ReadToEndAsync();
sr.Close();
stream.Close();
return str_responsefromjson;
}
这是方法(GetSteets):
private async Task<List<string>> GetStreets()
{
JObject jo = new JObject();
jo.Add("chars", AutoCompleteBox_Streets.Text);
jo.Add("city_id", "1");
JsonWorker jWorker = new JsonWorker();
var response = await jWorker.send("website", jo);
string str_responseformjson = await jWorker.get(response);
jo = JObject.Parse(str_responseformjson);
JArray ja = (JArray)jo["street"];
List<string> list_Streets = new List<string>();
foreach (var elem in ja)
{
list_Streets.Add(elem["title"].ToString());
}
return list_Streets;
}
这是我调用上述方法的时候:
private async void AutoCompleteBox_Streets_TextChanged(object sender, RoutedEventArgs e)
{
if (AutoCompleteBox_Streets.Text.Length.Equals(2))
{
AutoCompleteBox_Streets.ItemsSource = await GetStreets();
//On the string of code above in debug, ItemSource contains list of streets
}
}
当我在 Autocompletebox 中输入第二个字符时,它不显示下拉列表。请帮忙。