【发布时间】:2015-03-13 08:58:32
【问题描述】:
WPF:当用户在 ItemsControl 中的 texbox 内按下回车键时,我想将焦点移至 ItemsControl 中下一项中的文本框,或者如果用户在最后一项中,则创建一个新文本框。
为了更清楚:
场景 1
ItemsControl items:
[ textbox in item 1 ] <- user is here
[ textbox in item 2 ]
[ textbox in item 3 ]
回车后:
[ textbox in item 1 ]
[ textbox in item 2 ] <- user is here
[ textbox in item 3 ]
场景 2
ItemsControl 项:
[ textbox in item 1 ]
[ textbox in item 2 ]
[ textbox in item 3 ] <- user is here
回车后:
[ textbox in item 1 ]
[ textbox in item 2 ]
[ textbox in item 3 ]
[ textbox in item 4 ] <- user is here
如果有帮助,这里是项目数据模板的代码:
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="32"/>
</Grid.ColumnDefinitions>
<TextBox Text="{Binding Path=PartName, FallbackValue='----',TargetNullValue='----', NotifyOnSourceUpdated=True}" KeyDown="TextBox_KeyDown"/>
<Button Grid.Column="1" FontSize="10" x:Name="DeletePartButton" Click="DeletePartButton_Click" Height="22">Usuń</Button>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
编辑 2: 我使用 ItemsControl 是因为不需要选择功能。
编辑 3: 我找到了部分解决方案。它适用于将焦点移动到下一个元素,但不是新元素(这是这里最重要的功能)
private void PartNameTextBox_KeyDown(object sender, KeyEventArgs e)
{
var box = (TextBox)sender;
if (e.Key == Key.Enter)
{
var part = (PiecePart)box.DataContext;
int index = part.ParentPiece.Parts.IndexOf(part);
if (index == part.ParentPiece.PartCount - 1)
{
part.ParentPiece.Parts.Add(new PiecePart(GetNewPartName(part.ParentPiece)));
bool success = PartListBox.ApplyTemplate();
// try to force wpf to build a visual tree for the new item success = false :(
}
// throws out of bounds exception if a new item was added (and wasn't added to a visual tree)
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));
el.Focus();
}
}
【问题讨论】: