2014-07-23 15 views
1

我有一个TabControl的应用程序,并且在特定的选项卡中可以启动长计算。我希望用户确认离开选项卡并中止计算。 到目前为止,我创建了一个行为并将其附加到tabcontrol。 (代码在最后)。 我的问题:假设我想conifrm离开标签#3。 我选择选项卡#2 - >确认对话框弹出,我选择否(CanNavigateFromMe()== false),然后返回到选项卡#3。 再次,我选择选项卡#2并获得相同的行为。 我想第三次选择它 - 现在,单击标题不会触发CurrentChanging事件!对于行为WPF - 取消选择TabControl中的选项卡会导致问题

代码:

protected override void OnAttached() 
    { 
     base.OnAttached(); 
     AssociatedObject.Loaded += new System.Windows.RoutedEventHandler(AssociatedObject_Loaded); 
    } 

    void AssociatedObject_Loaded(object sender, System.Windows.RoutedEventArgs e) 
    { 
     // required in order to get CurrentItemChanging 
     AssociatedObject.IsSynchronizedWithCurrentItem = true; 

     AssociatedObject.Items.CurrentChanging += new CurrentChangingEventHandler(Items_CurrentChanging); 
    } 



    void Items_CurrentChanging(object sender, CurrentChangingEventArgs e) 
    { 
     var item = ((ICollectionView)sender).CurrentItem; 

     var view = item as FrameworkElement; 
     if (view == null) 
     { 
      return; 
     } 
     IAllowNavigation allowNavigation = view.DataContext as IAllowNavigation; 
     if ((allowNavigation != null) && 
      (allowNavigation.CanNavigateFromMe() == false)) 
     { 
      e.Cancel = true; 
      AssociatedObject.SelectedItem = view; 
     } 
    } 

回答

0

朋友一些帮助后,我发现我需要:在收集 1.调用刷新()如果取消选择。 2.保证原装做出选择,如果我决定允许选择(这涉及到用户输入和花费的时间,同时其他标签内ecents可以改变所选择的项目)

void Items_CurrentChanging(object sender, CurrentChangingEventArgs e) 
    { 
     var newItem = AssociatedObject.SelectedItem; 
     var item = ((ICollectionView)sender).CurrentItem; 


     var view = item as FrameworkElement; 
     if (view == null) 
     { 
      return; 
     } 
     IAllowNavigation allowNavigation = view.DataContext as IAllowNavigation; 
     if ((allowNavigation != null) && 
      (allowNavigation.CanNavigateFromMe() == false)) 
     { 
      e.Cancel = true; 
      AssociatedObject.SelectedItem = view; 

     } 
     else 
     { 
      AssociatedObject.SelectedItem = newItem; 
     } 

     ((ICollectionView)sender).Refresh(); 

    } 
+0

正如你指出这是重要的将所选项目保存在方法的开头,因为在您到达您的else语句时,它会以某种方式恢复到之前的值。 – denver

+0

我遇到同样的问题,如果您尝试导航并取消两次,它将无法在第三次使用。调用刷新不能解决问题。 – denver