WPF可搜索组合框中的导航
我有我的自定义组合框:WPF可搜索组合框中的导航,wpf,xaml,combobox,Wpf,Xaml,Combobox,我有我的自定义组合框: public class CustomComboBox : ComboBox { protected override void OnSelectionChanged(SelectionChangedEventArgs e) { // allow to go into items using up and down arrows without causing the text change e.Handled = true
public class CustomComboBox : ComboBox
{
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{
// allow to go into items using up and down arrows without causing the text change
e.Handled = true;
}
}
和xaml为:
<Window>
<Grid>
<wpfApplication1:CustomComboBox IsEditable="True"
Width="200"
Height="25"
IsTextSearchEnabled="False"
StaysOpenOnEdit="True"
x:Name="cb"
PreviewTextInput="Cb_OnPreviewTextInput"
ItemsSource="{Binding Projects}"
Text="{Binding Text}"
SelectionChanged="Cb_OnSelectionChanged">
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel />
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
</wpfApplication1:CustomComboBox>
</Grid>
</Window>
但这并没有起作用。最后编写了一个新模板,其中包含一个
列表视图
加上PreviewKeyDown中的自定义逻辑:
if (e.Key == Key.Up || e.Key == Key.Down)
{
listView.Focus();
listView.Items.MoveCurrentTo(listView.SelectedItem);
if (e.Key == Key.Up)
listView.Items.MoveCurrentToPrevious();
else
listView.Items.MoveCurrentToNext();
listView.SelectedItem = listView.Items.CurrentItem;
listView.ScrollIntoView(listView.Items.CurrentItem);
e.Handled = true;
return;
}
工作正常;)
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
if (_popup != null && e.Key == Key.Up || e.Key == Key.Down)
{
Dispatcher.BeginInvoke(DispatcherPriority.Input,
new Action(() =>
{
var c = _popup.Child;
var vs = c.GetChildOfType<VirtualizingStackPanel>();
vs.PageUp();
vs.Focus();
Keyboard.Focus(vs);
}));
}
base.OnPreviewKeyDown(e);
}
if (e.Key == Key.Up || e.Key == Key.Down)
{
listView.Focus();
listView.Items.MoveCurrentTo(listView.SelectedItem);
if (e.Key == Key.Up)
listView.Items.MoveCurrentToPrevious();
else
listView.Items.MoveCurrentToNext();
listView.SelectedItem = listView.Items.CurrentItem;
listView.ScrollIntoView(listView.Items.CurrentItem);
e.Handled = true;
return;
}