我在 LongListSelector 中有一个上下文菜单。此列表在运行时创建和更新。
<phone:PanoramaItem Header="{Binding Path=LocalizedResources.SavedGamesHeader, Source={StaticResource LocalizedStrings}}" Orientation="Horizontal">
<phone:LongListSelector Margin="0,0,-22,2" ItemsSource="{Binding SavedGames}">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" Margin="12,2,0,20" Width="432">
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Header="Remove" Click="RemoveSave_OnClick"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
<Image Margin="10,5,10,0" Height="173" Width="248" Source="{Binding Screen}" Stretch="Fill" HorizontalAlignment="Left"></Image>
<StackPanel Width="311" Margin="8,5,0,0" HorizontalAlignment="Left">
<TextBlock Tap="Save_OnTap" Tag="{Binding SavedGame}" Text="{Binding SaveName}" TextWrapping="Wrap" Margin="10,0" Style="{StaticResource PhoneTextExtraLargeStyle}" FontSize="{StaticResource PhoneFontSizeMedium}" Foreground="White" FontWeight="Bold" FontFamily="Arial Black" HorizontalAlignment="Left" />
<TextBlock Text="{Binding GameName}" TextWrapping="Wrap" Margin="10,-2,10,0" Style="{StaticResource PhoneTextSubtleStyle}" HorizontalAlignment="Left" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<TextBlock Text="Created on:" Margin="10,-2,10,0" Style="{StaticResource PhoneTextSubtleStyle}" />
<TextBlock Text="{Binding Created}" TextWrapping="Wrap" Margin="5,-2,10,0" Style="{StaticResource PhoneTextSubtleStyle}" />
</StackPanel>
</StackPanel>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</phone:PanoramaItem>
这是处理菜单项上的单击事件的方法
private void RemoveSave_OnClick(object sender, RoutedEventArgs e)
{
var menuItem = (MenuItem)sender;
var saveViewModel = menuItem.DataContext as SavesViewModel;
EmuStorageMgr.Instance.DeleteSave(saveViewModel.SavedGame.SaveFolder);
App.ViewModel.RescanSaves();
}
以下方法填充 SavedGames 列表
public ObservableCollection<SavesViewModel> SavedGames { get; private set; }
public void RescanSaves()
{
SavedGames.Clear();
var saves = EmuStorageMgr.Instance.GetSaves();
foreach (var save in saves)
{
SavedGames.Add(new SavesViewModel(save));
}
this.IsSavesLoaded = true;
NotifyPropertyChanged("SavedGames");
}
因此,当第一次填充 SavedGames 集合时,它可以完美运行,但是当集合发生变化(删除一些旧项目,添加新项目)时,我观察到一些奇怪的行为。当 OnClick 事件被触发时,我看到 menuItem.DataContext 不是针对我单击的菜单项,而是针对一些已删除的旧菜单项。