【问题标题】:Selection changing event in WPFWPF中的选择更改事件
【发布时间】:2014-03-03 00:25:10
【问题描述】:

我正在寻找一种方法来防止 WPF 项中的选择更改(现在是 Tab 控件,但将来需要对 ListBoxes、ListViews 和 ComboBoxes 进行此操作)。

我遇到了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 方法上设置了一个断点,但它从未被命中。

我做错了什么?

谢谢,

-弗林尼

【问题讨论】:

    标签: wpf tabcontrol selectionchanging


    【解决方案1】:

    您是否尝试将IsSynchronizedWithCurrentItem="True" 添加到您的TabControl

    【讨论】:

      【解决方案2】:

      感谢问题和答案,我能够在 c# 中做到这一点。 因此,对于任何需要使用 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."); 
          }
      

      【讨论】:

      • 请注意,如果您要取消选项卡更改,您还必须在代码中重置它,如 here 所述。如果我没有取消事件,我还必须在 TabControl 上手动设置新选项卡项。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多