";在使用“项目源”之前,项目必须为空;更新MapItemsControl.ItemsSource时
本文关键字:项目 更新 ItemsSource MapItemsControl quot 项目源 之前 | 更新日期: 2023-09-27 18:29:51
我有一个Map控件,里面有MapsItemControl:
<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;
当第一次将项目添加到地图时,此操作正确。但是,如果我想用新的soruce项目集合更新它,我会在itemCollection.ItemsSource = myItemCollection;
行中得到以下错误:
在使用项目源之前,项目必须为空
因此,我尝试在代码中添加一行,以便在再次设置源代码之前删除项目,但没有成功:
var itemCollection = MapExtensions.GetChildren((Map)MyMap).OfType<MapItemsControl>().FirstOrDefault();
itemCollection.Items.Clear();
itemCollection.ItemsSource = myItemCollection;
现在我在itemCollection.Items.Clear();
:行中得到以下异常
集合处于不可写入模式
如何更新MapItemsControl
中的项目?
如果您将ItemsSource与ItemsSource绑定,它似乎会被锁定。。。但如果你用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);
}
希望这有帮助:)
假设您继续使用相同的myItemCollection来保存当前信息(如果您正在绑定一个源,可能就是这样),那么您不需要重新绑定。相反,您需要抛出PropertyChanged事件,以便组件知道要使用源的当前内容进行更新。有关详细信息,请参阅绑定源教程和如何:从Microsoft实现属性更改通知。
尝试使用DataContext
属性。而且afaik你在使用时不需要写Clear。只需尝试一下:
var itemCollection = MapExtensions.GetChildren((Map)MyMap).OfType<MapItemsControl>().FirstOrDefault();
itemCollection.DataContext = myItemCollection;
Urmm。。怎么样
itemCollection.Items = itemCollection.Items.Clear();