当选择 ListBoxItem 时,如何将焦点设置到 ItemTemplate 中的控件?
我有一个使用 DataTemplate 呈现对象的列表框。 DataTemplate 包含一个文本框。当用户在列表框中选择一个项目时,我想将焦点设置到所选项目的文本框中。
我已经能够通过处理 ListBox.SelectionChanged 部分实现这一点,但它仅在用户单击 ListBox 选择项目时才起作用 - 如果用户切换到 ListBox 并使用箭头键来选择项目,则它不起作用即使调用了 TextBox.Focus(),仍选择该项目。
当用户使用键盘选择项目时,如何将焦点设置到文本框?
这是列表框的标记:
<ListBox Name="lb1" SelectionChanged="ListBox_SelectionChanged" ItemsSource="{Binding Items}" >
<ListBox.ItemTemplate>
<DataTemplate >
<TextBox></TextBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
这是处理代码:
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBoxItem lbi = (ListBoxItem)this.lb1.ItemContainerGenerator.ContainerFromItem(this.lb1.SelectedItem);
Visual v = GetDescendantByType<TextBox>(lbi);
TextBox tb = (TextBox)v;
tb.Focus();
}
I have a ListBox which presents objects using a DataTemplate. The DataTemplate contains a TextBox. When the user selects an item in the ListBox, I would like to set focus to the TextBox for the selected item.
I have been able to partially achieve this by handling ListBox.SelectionChanged, but it only works when the user clicks on the ListBox to select the item - it does not work if the user tabs into the ListBox and uses the arrow keys to select the item even though TextBox.Focus() is invoked.
How can I set focus to the TextBox when the user uses the keyboard to select an item?
Here is the markup for the ListBox:
<ListBox Name="lb1" SelectionChanged="ListBox_SelectionChanged" ItemsSource="{Binding Items}" >
<ListBox.ItemTemplate>
<DataTemplate >
<TextBox></TextBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Here is the handling code:
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBoxItem lbi = (ListBoxItem)this.lb1.ItemContainerGenerator.ContainerFromItem(this.lb1.SelectedItem);
Visual v = GetDescendantByType<TextBox>(lbi);
TextBox tb = (TextBox)v;
tb.Focus();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实现此目的的一种方法是将
SelectionChanged
事件处理程序中的tb.Focus()
替换为:这之所以有效,是因为在调度程序上调用
BeginInvoke
导致指定的代码在调度程序可用时运行 - 即在 WPF 完成内部事件处理之后。问题是,当列表项具有焦点时首次按向下箭头后,下一个列表项将被选中,其文本框将变为焦点,并且您将无法再次使用向下箭头移动选择。您可能也想编写一些代码来处理这种情况。
One way to do this is to replace the
tb.Focus()
from yourSelectionChanged
event handler with:This works because calling
BeginInvoke
on the dispatcher causes the specified code to run when the dispatcher is available - i.e. after WPF has finished handling the events internally.The catch is that, after you first press down arrow when a list item has focus, the next list item will became selected, its textbox will become focused and you will not be able to move selection again with the down arrow. You'll probably want to write some code to handle this case too.