WPF Horizontal Listbox Bad Keyboard Behavior

What a pain in the arse. Took me hours to find this.

I have a horizontal listbox resembling a filmstrip. It had images on it. A mouse click on the next item in the scrollbar produced a correct onselectionchanged event. Arrowing right or left did not product the correct selected index. An Arrow Key Right it went to index 0. An Arrow Key Left went to the last item in the list.

I overrode the listbox class with the following code:

public class HorizontalListBox : ListBox
{
protected override void OnKeyDown(KeyEventArgs e)
{
KeyDownHandler(this, e);
e.Handled = true;
}
void KeyDownHandler(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Left)
{
MoveUp();
}
if (e.Key == System.Windows.Input.Key.Right)
{
MoveDown();
}
}
void MoveUp()
{
if (this.SelectedIndex > 0)
{
this.SelectedIndex = this.SelectedIndex – 1;
}
}
void MoveDown()
{
try
{
this.SelectedIndex = this.SelectedIndex + 1;
}
catch { }
}
}

Happy coding!
Linda

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.