WPF:当用户在 ItemsControl 中的文本框中按下 Enter 键时,我想将焦点移动到 ItemsControl 中下一项中的文本框,或者如果用户位于最后一项中,则创建一个新文本框。
\n\n更清楚地说:
\n\n场景1
\n\nItemsControl items:\n[ textbox in item 1 ] <- user is here\n[ textbox in item 2 ]\n[ textbox in item 3 ]\nRun Code Online (Sandbox Code Playgroud)\n\n按回车后:
\n\n[ textbox in item 1 ]\n[ textbox in item 2 ] <- user is here\n[ textbox in item 3 ]\nRun Code Online (Sandbox Code Playgroud)\n\n场景2
\n\n项目控制项目:
\n\n[ textbox in item 1 ]\n[ textbox in item 2 ]\n[ textbox in item 3 ] <- user is here\nRun Code Online (Sandbox Code Playgroud)\n\n按回车后:
\n\n[ textbox in item 1 ]\n[ textbox in item 2 ]\n[ textbox in item 3 ]\n[ textbox in item 4 ] <- user is here\nRun Code Online (Sandbox Code Playgroud)\n\n如果有帮助,这里是项目数据模板的代码:
\n\n<ItemsControl.ItemTemplate>\n <DataTemplate>\n <Grid Background="White">\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width="*"/>\n <ColumnDefinition Width="32"/>\n </Grid.ColumnDefinitions>\n <TextBox Text="{Binding Path=PartName, FallbackValue=\'----\',TargetNullValue=\'----\', NotifyOnSourceUpdated=True}" KeyDown="TextBox_KeyDown"/>\n <Button Grid.Column="1" FontSize="10" x:Name="DeletePartButton" Click="DeletePartButton_Click" Height="22">Usu\xc5\x84</Button>\n </Grid>\n </DataTemplate>\n</ItemsControl.ItemTemplate>\nRun Code Online (Sandbox Code Playgroud)\n\n编辑 2:\n我使用 ItemsControl 因为不需要选择功能。
\n\n编辑3:\n我找到了部分解决方案。它适用于将焦点移至下一个元素,但不适用于新元素(这是这里最重要的功能)
\n\n private void PartNameTextBox_KeyDown(object sender, KeyEventArgs e)\n {\n var box = (TextBox)sender;\n\n if (e.Key == Key.Enter)\n {\n var part = (PiecePart)box.DataContext;\n int index = part.ParentPiece.Parts.IndexOf(part);\n if (index == part.ParentPiece.PartCount - 1)\n {\n part.ParentPiece.Parts.Add(new PiecePart(GetNewPartName(part.ParentPiece)));\n bool success = PartListBox.ApplyTemplate();\n // try to force wpf to build a visual tree for the new item success = false :(\n }\n// throws out of bounds exception if a new item was added (and wasn\'t added to a visual tree)\n var el = ((UIElement)VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(PartListBox, 0),0),1),0),0),++index),0),0));\n el.Focus();\n }\n }\nRun Code Online (Sandbox Code Playgroud)\n
Listbox.SelectedIndex = 0;
private void Listbox_OnKeyUp(object sender, KeyEventArgs e)
{
if (e.Key== Key.Enter)
{
if(Listbox.Items.Count-1>Listbox.SelectedIndex)
Listbox.SelectedIndex++;
else
Listbox.SelectedIndex=0;
}
}
Run Code Online (Sandbox Code Playgroud)
当用户专注于您的列表框时,此功能有效。