2017-03-08 41 views
0

我有一個ComboBox動態創建的,我已經設置下列屬性:防止項目選擇在組合框(或,AutoSuggestTextBox而不ItemSelection)

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內的相鄰單元格。

我的問題是,在使用向上箭頭鍵時,我需要將焦點導航到上方/下方控件,而不是ComboBox的默認選擇項目。

我該怎麼做?

回答

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

這工作,謝謝!我還需要設置'IsTabStop = true',這在我的默認組合框樣式中設置爲false。 –

相關問題