Is there a way to cancel TabControl.Items.CurrentChanging?

空扰寡人 提交于 2019-12-01 18:19:17
ThomasAndersson

I don't know the exact reason why this happens, and it annoys me greatly.

But here's my workaround for it:

In the sample below, checkbox is "locking" the current tab. So checked means user can't change tab.

void Items_CurrentChanging(object sender, CurrentChangingEventArgs e)
{
    if (checkBox1.IsChecked.Value)
    {
        var item = ((ICollectionView)sender).CurrentItem;

        e.Cancel = true;

        tabControl1.SelectedItem = item;
    }
}

Basically, what happens is (if I understand this correctly) the visual tree gets updated, but the logical tree does not. The above way forces the visual to sync with the logical tree.

You can also handle the PreviewLostKeyboardFocus event on each TabItem, and set the Handled property of the event arguments to true to prevent switching to another tab:

protected void tabItem_PreviewLostKeyboardFocus(object sender,
    KeyboardFocusChangedEventArgs e)
{
    if (!ValidateTabItem((TabItem) sender)) {
        e.Handled = true;
    }
}

See http://www.netframeworkdev.com/windows-presentation-foundation-wpf/how-to-cancel-navigation-between-tabitems-in-a-tabcontrol-84994.shtml.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!