我刚刚遇到了上下文菜单的严重问题,几个小时都无法解决。
为了重现该问题,我在 Visual Studio 2012 中使用 Windows Phone 8 的应用程序模板创建了一个全新的 Panorama 应用程序。我通过 nugget 安装了 Windows Phone 工具包,并在绑定到 Items 的第一个长列表选择器的数据模板中添加了上下文菜单
<StackPanel Margin="0,-6,0,12">
<TextBlock Text="{Binding LineOne}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" FontSize="{StaticResource PhoneFontSizeExtraLarge}"/>
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Header="{Binding LineOne}" Click="MenuItem_Click_1" Tag="{Binding}">
</toolkit:MenuItem>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</StackPanel>
我将标头设置为 LineOne 属性以便于调试。我附上了以下事件:
private void MenuItem_Click_1(object sender, RoutedEventArgs e)
{
var itemViewModel = (ItemViewModel)((MenuItem)sender).Tag;
App.ViewModel.Items.Remove(itemViewModel);
App.ViewModel.Items.Add(new ItemViewModel { LineOne = "Test", LineTwo = "Test", LineThree = "Test" });
}
我运行该应用程序并使用上下文菜单删除第一项。第一项消失,名为 Test 的新项按预期出现在列表底部。如果我持有这个新项目,菜单项将绑定到“运行时一个”(已删除的项目)。
这是我可以重现错误的最简单的代码,但在我的真实应用程序中,我遇到了几乎相同的问题,并且有更有意义的代码用于在不同的方法甚至不同的页面中添加和删除。我有一个命令绑定,但由于数据绑定错误,该命令在错误的视图模型中使用错误的参数运行。
知道为什么会发生这种情况吗?