Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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

like image 663
Faraz Avatar asked May 11 '15 05:05

Faraz


1 Answers

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;
like image 118
Nacimota Avatar answered Sep 20 '22 07:09

Nacimota