我正在开发一个Windows Phone 8,我有一个选择列表框和这个方法:
private void locationsList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
ARLocation item = (ARLocation)locationsList.SelectedItem;
NavigationService.Navigate(new Uri("/Views/MapPage.xaml", UriKind.Relative));
locationsList.SelectedItem = null;
}
当我执行locationsList.SelectedItem = null;
时,会再次触发SelectionChanged
事件。
当我清除SelectedItem时,如何避免触发事件?
答案 0 :(得分:3)
除非您不想取消订阅该活动,否则您无法避免 - 您正在更改所选项目,因此它会触发该活动。
您可以尝试做这样的事情 - 取消订阅然后订阅活动:
locationsList.SelectioChanged -= locationsList_SelectionChanged;
locationsList.SelectedItem = null;
locationsList.SelectioChanged += locationsList_SelectionChanged;
但在这种情况下执行检查可能更容易:
private void locationsList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if ((sender as ListBox).SelectedItem != null)
{
ARLocation item = (ARLocation)locationsList.SelectedItem;
NavigationService.Navigate(new Uri("/Views/MapPage.xaml", UriKind.Relative));
locationsList.SelectedItem = null;
}
}
或者您可以提供一个布尔值来通知事件应该跳过它:
private bool SkipEvent = false;
private void locationsList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if (SkipEvent) return;
ARLocation item = (ARLocation)locationsList.SelectedItem;
NavigationService.Navigate(new Uri("/Views/MapPage.xaml", UriKind.Relative));
// Skip block:
try
{
SkipEvent = true;
locationsList.SelectedItem = null;
}
finally { SkipEvent = false; }
}