我正在尝试将图钉添加到Bing地图中。推针来自JSON提要。我想得到这样的东西: 我的代码单独第一次不起作用,我不明白为什么。 我的地图ViewModel是
public class MapViewModel : INotifyPropertyChanged
{
public static ObservableCollection<PushpinModel> pushpins = new ObservableCollection<PushpinModel>();
public static ObservableCollection<PushpinModel> Pushpins
{
get { return pushpins; }
set { pushpins = value; }
}
}
Map xaml cs是:
//Map.xaml.cs
public partial class Map : PhoneApplicationPage
{
#define DEBUG_AGENT
private IGeoPositionWatcher<GeoCoordinate> watcher;
private MapViewModel mapViewModel;
public Map()
{
InitializeComponent();
mapViewModel = new MapViewModel();
this.DataContext = mapViewModel;
}
private void page_Loaded(object sender, RoutedEventArgs e)
{
if (watcher == null)
{
#if DEBUG_AGENT
watcher = new Shoporific.My.FakeGPS();
#else
watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
#endif
}
watcher.Start();
mapViewModel.Center = watcher.Position.Location;
PushpinModel myLocation = new PushpinModel() { Location = mapViewModel.Center, Content = "My Location" };
MapViewModel.Pushpins.Add(myLocation);
myLocation.RefreshNearbyDeals();
watcher.Stop();
}
}
最后,PushPinModelClass:
public class PushPinModel
{
public void RefreshNearbyDeals()
{
System.Net.WebClient wc = new WebClient();
wc.OpenReadCompleted += wc_OpenReadCompleted;
wc.OpenReadAsync(" a valid uri");
}
void wc_OpenReadCompleted(object sender, System.Net.OpenReadCompletedEventArgs e)
{
var jsonStream = e.Result;
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Deal[]));
Deal[] deals = (ser.ReadObject(jsonStream) as Deal[]);
if (deals.Any())
{
var currentLocation = MapViewModel.Pushpins.Where(pin => pin.Content == "My Location");
MapViewModel.Pushpins = new ObservableCollection<PushpinModel>();
foreach (var deal in deals)
MapViewModel.Pushpins.Add(new PushpinModel()
{
Content = deal.Store,
Location = new GeoCoordinate(deal.Location.Latitude, deal.Location.Longtitude),
Offers = deal.Offers,
});
}
}
}
我有点困惑,除了“我的位置”之外的Pushpins不会仅在第一次出现。它们第二次出现时是预期的(如果我向后导航然后再次移动到地图屏幕)。
答案 0 :(得分:1)
在wc_OpenReadCompleted
内,您正在重新实例化MapViewModel.Pushpins
。
仅将构造函数调用ObservableCollection
一次(在MainViewModel
内)。再次调用它会弄乱我假设你在xaml页面中的绑定。
我相信你应该删除PushpinViewModel中的那一行,或者改为调用MainViewModel.Pushpins.Clear()
(取决于你想要完成的事情)。