在Combobox中防止项目选择(或者,没有ItemSelection的AutoSuggestTextBox)

时间:2017-03-08 04:54:13

标签: c# wpf combobox

我动态创建了ComboBox,并设置了以下属性:

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);

这个ComboBox是可编辑的,因为我希望它像AutoSuggestTextBox一样。它是动态Grid的一部分,它是一个类似于表的结构,具有相同大小的行和列。我正在使用箭头键将焦点遍历到Grid内的相邻单元格。

我的问题是,使用Up&当焦点在这些ComboBox上时,向下箭头键,我希望焦点导航到上/下控件而不是ComboBox的选择它的项目的默认行为。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您需要创建一个覆盖ComboBox方法的自定义OnPreviewKeyDown类:

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);