WPF中的选择更改事件

问题描述:

我正在寻找一种方法来阻止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

你有没有尝试添加IsSynchronizedWithCurrentItem="True"TabControl

+0

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

感谢问题和答案,我能够在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."); 
    }