我正在开发一个可以获取IP地址并检查城市,州,纬度,经度等的模块。所有代码都没有问题但是如何检索数据并将其显示在我的TextBlock上?
public class TestGeo
{
GeoLoc _geoLoc = new GeoLoc();
internal GeoLoc GetMyGeoLocation()
{
try
{
var request = WebRequest.Create(new Uri("http://geoiptool.com/data.php")) as HttpWebRequest;
if (request != null)
{
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727)";
using (var webResponse = request.GetResponse() as HttpWebResponse)
if (webResponse != null)
{
using (var reader = new StreamReader(webResponse.GetResponseStream()))
{
var doc = new XmlDocument();
doc.Load(reader);
var nodes = doc.GetElementsByTagName("marker");
// Guard.AssertCondition(nodes.Count > 0, "nodes", new object());
var marker = nodes[0] as XmlElement;
Guard.AssertNotNull(marker, "marker");
_geoLoc.City = marker.GetAttribute("city");
_geoLoc.Country = marker.GetAttribute("country");
_geoLoc.Code = marker.GetAttribute("code");
_geoLoc.Host = marker.GetAttribute("host");
_geoLoc.Ip = marker.GetAttribute("ip");
_geoLoc.Latitude = marker.GetAttribute("lat");
_geoLoc.Longitude = marker.GetAttribute("lng");
_geoLoc.State = GetMyState(_geoLoc.Latitude, _geoLoc.Longitude);
return _geoLoc;
}
}
}
return new GeoLoc();
}
catch (Exception ex)
{
throw;
}
}
答案 0 :(得分:0)
这是一种快速而肮脏的方式......当然,由于你没有向我们展示你的GeoLoc
课程的样子,所以有点难以看清。
启动一个新的WPFApplication并将其添加到后面的代码中:
public MainWindow()
{
GeoLoc location = new TestGeo().GetMyGeoLocation();
LocationTextBlock.Text = location.ToString();
DataContext = this;
}
将其放入<Grid>
和</Grid>
元素之间的XML页面中:
<TextBlock Name="LocationTextBlock" />
当然,如果你没有覆盖ToString
方法,那么就不会显示任何有用的东西......在这种情况下,要么override Object.ToString()
,要么用这个替换构造函数中的那一行:
LocationTextBlock.Text = location.SomeProperty; // Use a string property of your class