首先看一段代码:
private void tv_SelectedIemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { var dv = (tv.SelectedItem as TreeViewItem).Header; HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://localhost:19976/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); #region 注释这段代码就可以正确执行 HttpResponseMessage response = client.GetAsync("api/Department").Result; response.EnsureSuccessStatusCode(); if (response.IsSuccessStatusCode) { var ds = response.Content.ReadAsAsync<IEnumerable<string>>(); } #endregion }
这部分是TreeView的ItemChanged事件,通过点击事件,调用WEBAPI,这里WEBAPI随便写个简单的。
现在问题是,只要点击TreeViewItem子节点,就会运行两次,第一次是子节点,第二次就是父节点了。
注释掉调用WEBAPI的代码就可以正确运行,只执行一次。
找了好久,没找到合适的解决办法。希望有遇到的大神帮忙解决下,或者提供个思路。
WEBAPI 为ASP.NET MVC4的WEBAPI。WEBAPI是正确没问题的。
提问完发现在CSDN上有人已经回答了。新建个线程即解决了。
private void tv_SelectedIemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { var dv = (tv.SelectedItem as TreeViewItem).Header; Thread thread = new Thread(NewMethod); thread.Start(); } private static void NewMethod() { HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://localhost:19976/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); #region 注释这段代码就可以正确执行 HttpResponseMessage response = client.GetAsync("api/Department").Result; response.EnsureSuccessStatusCode(); if (response.IsSuccessStatusCode) { var ds = response.Content.ReadAsAsync<IEnumerable<string>>(); } #endregion }