我有一个带有 MapsItemControl 的 map 控件:
<maps:Map x:Name="MyMap">
<maptk:MapExtensions.Children>
<maptk:MapItemsControl>
<maptk:MapItemsControl.ItemTemplate>
<DataTemplate>
. . .
</DataTemplate>
</maptk:MapItemsControl.ItemTemplate>
</maptk:MapItemsControl>
</maptk:MapExtensions.Children>
</maps:Map>
我通过以下方式在代码中填充 MapItemsControl
:
var itemCollection = MapExtensions.GetChildren((Map)MyMap).OfType<MapItemsControl>().FirstOrDefault();
itemCollection.ItemsSource = myItemCollection;
这在第一次向 map 添加项目时工作正常。但是如果我想用新的源项目集合更新它,我会在 itemCollection.ItemsSource = myItemCollection;
行中收到以下错误:
Items must be empty before using Items Source
所以,我尝试在我的代码中添加一行,以便在再次设置源之前删除项目,但没有成功:
var itemCollection = MapExtensions.GetChildren((Map)MyMap).OfType<MapItemsControl>().FirstOrDefault();
itemCollection.Items.Clear();
itemCollection.ItemsSource = myItemCollection;
现在我在 itemCollection.Items.Clear();
行中得到以下异常:
Collection is in non writeable mode
如何更新 MapItemsControl
中的项目?
最佳答案
如果您将 Items 与 ItemsSource 绑定(bind),似乎 Items 会被锁定...但是如果您使用 Item.Add(item) 添加每个项目,它会正常工作。 所以我最终做的是这样的:
var itemCollection = MapExtensions.GetChildren((Map)MyMap)
.OfType<MapItemsControl>().FirstOrDefault();
if(itemCollection != null && itemCollection.Items.Count >0)
{
itemCollection.Items.Clear();
}
foreach(var item in YourPushpinCollection)
{
itemCollection.Items.Add(item);
}
希望这有帮助:)
关于c# - "Items must be empty before using Items Source"更新 MapItemsControl.ItemsSource 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18574819/