开发者

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

There is unfortunately no TabControl.SelectionChanging event (Selector.SelectionChanging), I am struggling to implement this behavior so I can cancel the changing request.

I tried to handle the TabControl.Items.CurrentChanging (the Items property is and ItemCollection) event setting e.Cancel (of the CurrentChangingEventArgs) to true, but the UI is is updated with the new tab a开发者_高级运维lthough the item is not changed in the collection.

Is there any way to prevent user from switching to a different TabItem when a condition is dissatisfied?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜