Search code examples
wpftabcontrolselectionchanging

Selection changing event in WPF


I am looking for a way to prevent a selection change in WPF items (the Tab control right now, but in the future this will need to be done for ListBoxes, ListViews and ComboBoxes).

I came across this thread and attempted to use the same technique that was marked as the answer.

In that technique you retrieve the CollectionView for the tab control's items and handle the CollectionView's CurrentChanging event to prevent the selection from occurring.

For some reason, the CurrentChanging event is never being fired in my code.

Here is my very simple user control that I am working with. It has a tab control with 3 tabs.

(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>

In my VB.NET code for the user control, I am simply retrieving the CollectionView for the tab control's items and using the AddHandler method to watch for the event.

(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

I put a break point on the MainTabControl_ItemSelecting method, but it is never hit.

What am I doing wrong?

Thanks,

-Frinny


Solution

  • Have you tried adding IsSynchronizedWithCurrentItem="True" to your TabControl?