Faraz
Faraz

Reputation: 893

how to navigate between tabitem with Left and Right Key in WPF

hi everybody I want used shortcut key (using left and right key) in wpf and tabcontrol to navigation between tabitem I set code in Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)

like this:

switch (e.Key)
            {
                case Key.Right:
                    if (tbControl.TabIndex == 0)
                        tbControl.TabIndex = 1;
                    break;

                case Key.Left:
                    if (tbControl.TabIndex == 0)
                        tbControl.TabIndex = 1;
                    break;
            }

but it's not do anything I want navigation between tabitem with left and right key thanks

Upvotes: 6

Views: 898

Answers (1)

Nacimota
Nacimota

Reputation: 23225

You are using TabControl.TabIndex when you should be using TabControl.SelectedIndex, like so:

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    switch (e.Key)
    {
        case Key.Right:
            if (tbControl.SelectedIndex == 0)
                tbControl.SelectedIndex = 1;
            break;
        case Key.Left:
            if (tbControl.SelectedIndex == 1)
                tbControl.SelectedIndex = 0;
            break;
    }
}

TabIndex is common to all controls, and represents the order in which controls are focused when the user presses the Tab key. SelectedIndex is specific to selector controls (e.g. TabControl, ListBox, ComboBox, etc.) and represents the index of the currently selected item in said control.

Also, if you wanted this to work with more than two tabs, I would change your case statements to something more like this:

case Key.Right:
    if (tbControl.SelectedIndex < tbControl.Items.Count - 1)
        tbControl.SelectedIndex++;
    break;

case Key.Left:
    if (tbControl.SelectedIndex > 0)
        tbControl.SelectedIndex--;
    break;

Upvotes: 4

Related Questions