2014-07-23 99 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

相關問題