c# - "Items must be empty before using Items Source"更新 MapItemsControl.ItemsSource 时

标签 c# xaml map windows-phone-8

我有一个带有 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/

相关文章:

c# - 在 codedom 中使用动态对象创建 LINQ 查询

c# - 使用 Polly 从异步函数进行重试

c# - 在 ProgressBar 控件模板中为 WPF ImageBrush 设置动画

c# - 在 Windows 8 中处理方向

c++ - 使用 std::map<K,V> 其中 V 没有可用的默认构造函数

java - TreeMap lastKey 查找时间

c# - 如何编写一个可以处理 Task 和 ValueTask 的方法?

c# - 使用 foreach 枚举内部字典

xaml - XAML顶部垂直对齐标签和文本 block

c++ - std::map 插入另一个 map