在TabControl中取消选择选项卡会导致问题

本文关键字:问题 选项 TabControl 取消 选择 | 更新日期: 2023-09-27 18:14:34

我有一个带有TabControl的应用程序,在一个特定的选项卡中可以开始长时间的计算。我希望用户确认离开选项卡并终止计算。到目前为止,我创建了一个Behavior并将其附加到tabcontrol上。(代码在最后)。我的问题是:假设我想确认离开标签#3。我选择选项卡#2 ->确认对话框弹出,我选择no (CanNavigateFromMe() == false),然后我返回选项卡#3。同样,我选择标签#2,得到相同的效果。我想第三次选择它-现在,单击标题不会触发CurrentChanging事件!

行为代码:

    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;
        }
    }

在TabControl中取消选择选项卡会导致问题

在朋友的帮助下,我发现我需要:1. 如果取消选择,则对集合调用Refresh()。2. 如果我决定允许选择,请确保原始选择是进行的(这涉及用户输入并需要时间,同时其他选项卡中的事件可以更改所选项)

    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();
    }