测试代码 请勿商用
定义数据读取service 的接口
View Code
using System; using System.Linq; namespace SimpleMvvmWpf1 { public interface ICustomerServiceAgent { void GetSearch(SearchType searchType, string keyword, Action<string, string, Exception> callBack); } }
实现接口
View Code
using System; using System.Linq; using System.Net; using System.IO; using System.Text; using HtmlAgilityPack; namespace SimpleMvvmWpf1 { public class MockCustomerServiceAgent : ICustomerServiceAgent { public void GetSearch(SearchType searchType, string keyword, Action<string,string,Exception> callBack) { try { WebClient client = new WebClient(); client.Encoding = Encoding.UTF8; client.DownloadStringCompleted += (s, e) => { HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(e.Result); if (searchType == SearchType.mv) { foreach (HtmlNode link in doc.DocumentNode.SelectNodes("/html[1]/body[1]/div[7]/div[1]/div[3]/div[2]/div[2]/ul")) { foreach (HtmlNode node in link.SelectNodes("/html[1]/body[1]/div[7]/div[1]/div[3]/div[2]/div[2]/ul[1]/li")) { } } callBack("mv", "", null); } else { foreach (HtmlNode link in doc.DocumentNode.SelectNodes("/html[1]/body[1]/div[7]/div[1]/div[3]/div[2]/div[2]/ul")) { foreach (HtmlNode node in link.SelectNodes("/html[1]/body[1]/div[7]/div[1]/div[3]/div[2]/div[2]/ul[1]/li")) { } } callBack("", "artist", null); } }; client.DownloadStringAsync(new Uri(string.Format("http://www.yinyuetai.com/search?searchType={0}&keyword={1}", searchType, keyword))); } catch (WebException e) { callBack("", "", e); } catch (Exception e) { callBack("", "", e); } } } }
ViewModel中调用
View Code
serviceAgent.GetSearch(SearchType.artist, "谢", (result,list, error) => { //返回数据 判断 if(error==null) { //通过SearchType 判断 使用哪个数据 } });
转载请注明文章出处:http://www.cnblogs.com/thinkaspx