2013-03-27 50 views
1

我正在尋找一種方法來阻止WPF項目(Tab控件現在,但將來需要爲ListBoxes,ListViews和ComboBoxes完成)中的選擇更改。WPF中的選擇更改事件

我遇到了this thread並試圖使用標記爲答案的相同技巧。

在該技術中,您將檢索標籤控件項目的CollectionView,並處理CollectionView's CurrentChanging event以防止發生選擇。

由於某種原因,CurrentChanging事件從未在我的代碼中被觸發。

這是我正在使用的非常簡單的用戶控件。 它有一個帶有3個選項卡的選項卡控件。

(XAML)

<UserControl x:Class="UserControlWithTabs" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     mc:Ignorable="d" 
     d:DesignHeight="300" d:DesignWidth="300"> 

    <TabControl x:Name="MainTabControl"> 
     <TabItem Header="First Tab">Content for the first tab</TabItem> 
     <TabItem Header="Second Tab">Content for the second tab</TabItem> 
     <TabItem Header="Third Tab">Content for the third tab</TabItem> 
    </TabControl> 
</UserControl> 

在用戶控件我的VB.NET代碼,我只是檢索的CollectionView選項卡控件的項目和使用AddHandler方法來監控事件。

(VB.NET)

Public Class UserControlWithTabs 
    Private WithEvents mainTabCollectionView As CollectionView 
    Private Sub UserControlWithTabs_Loaded(sender As Object, e As System.Windows.RoutedEventArgs) Handles Me.Loaded 
    mainTabCollectionView = CollectionViewSource.GetDefaultView(MainTabControl.Items) 
    AddHandler mainTabCollectionView.CurrentChanging, AddressOf MainTabControl_ItemSelecting 
    End Sub 

    Private Sub MainTabControl_ItemSelecting(ByVal sender As Object, ByVal e As System.ComponentModel.CurrentChangingEventArgs) 

    End Sub 
End Class 

我穿上MainTabControl_ItemSelecting方法一個破發點,但從來沒有擊中。

我在做什麼錯?

感謝,

-Frinny

回答

1

你有沒有嘗試添加IsSynchronizedWithCurrentItem="True"TabControl

+0

非常感謝! – Frinavale 2013-03-27 16:37:35

0

感謝問題和答案,我能夠在c#中做到這一點。 所以對於任何需要類似這樣的代碼的人來說,這裏是我做的:

mytab.IsSynchronizedWithCurrentItem = true; 
    mytab.Items.CurrentChanging += new CurrentChangingEventHandler(Items_CurrentChanging); 

    private void Items_CurrentChanging(object sender, CurrentChangingEventArgs e) 
    { 
     if (e.IsCancelable) 
     { 
      FrameworkElement elemfrom = ((ICollectionView)sender).CurrentItem as FrameworkElement; 
      FrameworkElement elemto = mytab.SelectedItem as FrameworkElement; 
     } 
     Console.WriteLine("tab is changing."); 
    }