Vijay Chavda
Vijay Chavda

Reputation: 862

Prevent Item selection in Combobox (or, AutoSuggestTextBox without ItemSelection)

I have a ComboBox created dynamically, and I have set the following properties:

var keyUpHandler = new KeyEventHandler(
(s, e) =>
{
    var cell = s as UIElement;

    if (e.Key == Key.Up)
    {
        cell.MoveFocus(new TraversalRequest(FocusNavigationDirection.Up));
    }
    else if (e.Key == Key.Right)
    {
        cell.MoveFocus(new TraversalRequest(FocusNavigationDirection.Right));
    }
    else if (e.Key == Key.Down)
    {
        cell.MoveFocus(new TraversalRequest(FocusNavigationDirection.Down));
    }
    else if (e.Key == Key.Left)
    {
        cell.MoveFocus(new TraversalRequest(FocusNavigationDirection.Left));
    }
});

ComboBox cb = new ComboBox();
Grid.SetRow(cb, row);
Grid.SetColumn(cb, col);
cb.IsEditable = true;
cb.DataContext = myDataContext;
cb.ItemsSource = myDataItems;
cb.FocusVisualStyle = null;
cb.KeyUp += keyUpHandler;
cb.Resources.Add(SystemParameters.VerticalScrollBarWidthKey, 0.0);
myGrid.Children.Add(cb);

This ComboBox is editable as I wanted it to act like an AutoSuggestTextBox. It is a part of a dynamic Grid which is a table like structure with equal sized rows and columns. I am using arrow keys to traverse focus to adjacent cells within the Grid.

My problem is, on using Up & Down arrow keys when focus is on these ComboBox, I want focus to be navigated to above/below controls instead of ComboBox's default behavior of selecting it's items.

How can I do this?

Upvotes: 0

Views: 118

Answers (1)

mm8
mm8

Reputation: 169160

You need to create a custom ComboBox class that overrides the OnPreviewKeyDown method:

public class CustomComboBox : ComboBox
{
    protected override void OnPreviewKeyDown(KeyEventArgs e)
    {
        if (e.Key == Key.Up)
        {
            this.MoveFocus(new TraversalRequest(FocusNavigationDirection.Up));
        }
        else if (e.Key == Key.Right)
        {
            this.MoveFocus(new TraversalRequest(FocusNavigationDirection.Right));
        }
        else if (e.Key == Key.Down)
        {
            this.MoveFocus(new TraversalRequest(FocusNavigationDirection.Down));
        }
        else if (e.Key == Key.Left)
        {
            this.MoveFocus(new TraversalRequest(FocusNavigationDirection.Left));
        }
        else
        {
            base.OnPreviewKeyDown(e);
        }
    }
}

ComboBox cb = new CustomComboBox();
Grid.SetRow(cb, row);
Grid.SetColumn(cb, col);
cb.IsEditable = true;
cb.DataContext = myDataContext;
cb.ItemsSource = myDataItems;
cb.FocusVisualStyle = null;
cb.Resources.Add(SystemParameters.VerticalScrollBarWidthKey, 0.0);
myGrid.Children.Add(cb);

Upvotes: 1

Related Questions