[英]How to set multiple pushpins from code-behind (WP8)?
我嘗試添加多個圖釘進行映射。
這是XAML:
<maps:Map ZoomLevel="8" Height="500" x:Name="map1" Width="415" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,0,0,0">
<toolkit1:MapExtensions.Children>
<toolkit1:MapItemsControl x:Name="PushpinCollection">
<toolkit1:MapItemsControl.ItemTemplate>
<DataTemplate>
<toolkit1:Pushpin GeoCoordinate="{Binding Coords}" Content="{Binding Name}"/>
</DataTemplate>
</toolkit1:MapItemsControl.ItemTemplate>
</toolkit1:MapItemsControl>
</toolkit1:MapExtensions.Children>
</maps:Map>
這是代碼:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var xmlDataSource = new XmlDataSource();
var sigCol = new SignalCollection(xmlDataSource);
var allSignals = await sigCol.GetData(false, false, "UA");
ObservableCollection<IssueDescription> signalsWithCoords = new ObservableCollection<IssueDescription>();
foreach (var signal in allSignals)
{
if (signal.Coords != null)
{
signalsWithCoords.Add(signal);
}
}
PushpinCollection.ItemsSource = signalsWithCoords;
}
但是最后一個字符串拋出NullReferenceException。 怎么了?
正如我檢查的PushpinCollection
存在(不為null),並且以下代碼應該工作:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var xmlDataSource = new XmlDataSource();
var sigCol = new SignalCollection(xmlDataSource);
var allSignals = await sigCol.GetData(false, false, "UA");
ObservableCollection<IssueDescription> signalsWithCoords = new ObservableCollection<IssueDescription>();
foreach (var signal in allSignals)
{
if (signal.Coords != null)
{
signalsWithCoords.Add(signal);
}
}
MapItemsControl PushpinCol = MapExtensions.GetChildren(map1).FirstOrDefault(x => x is MapItemsControl) as MapItemsControl;
PushpinCol.ItemsSource = signalsWithCoords;
}
進一步研究發現這似乎是一個小錯誤。 在源代碼中, DependencyProperty NameProperty
被注冊為"ItemTemplate"
-可能阻止從代碼中按名稱獲取它。
編輯 -評論后
如果在Items.Count > 0
並嘗試更改ItemsSource時,在源代碼中多挖掘一點信息,就會表明MapExtension引發了此異常。 這是一種允許您更改ItemsSource的方法:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var xmlDataSource = new XmlDataSource();
var sigCol = new SignalCollection(xmlDataSource);
var allSignals = await sigCol.GetData(false, false, "UA");
ObservableCollection<IssueDescription> signalsWithCoords = new ObservableCollection<IssueDescription>();
foreach (var signal in allSignals)
{
if (signal.Coords != null)
{
signalsWithCoords.Add(signal);
}
}
MapItemsControl PushpinCol = MapExtensions.GetChildren(map1).FirstOrDefault(x => x is MapItemsControl) as MapItemsControl;
if (PushpinCol != null && PushpinCol.ItemsSource != null)
{
(PushpinCol.ItemsSource as IList).Clear();
PushpinCol.ItemsSource = null;
}
PushpinCol.ItemsSource = signalsWithCoords;
}
另一方面,請考慮將您的Collection設為靜態,並將其設置為ItemsSource一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.