[英]Move to the next control on enter/return press in Windows 8 Store application
我有一個帶有大量文本框的Windows 8商店應用程序。 當我按下鍵盤上的Enter鍵時,我希望將focues移動到下一個控件。
我怎樣才能做到這一點?
謝謝
您可以處理TextBoxes上的KeyDown / KeyUp事件(取決於您是否要在按鍵的開頭或結尾處轉到下一個事件)。
示例XAML:
<TextBox KeyUp="TextBox_KeyUp" />
代碼背后:
private void TextBox_KeyUp(object sender, KeyRoutedEventArgs e)
{
TextBox tbSender = (TextBox)sender;
if (e.Key == Windows.System.VirtualKey.Enter)
{
// Get the next TextBox and focus it.
DependencyObject nextSibling = GetNextSiblingInVisualTree(tbSender);
if (nextSibling is Control)
{
// Transfer "keyboard" focus to the target element.
((Control)nextSibling).Focus(FocusState.Keyboard);
}
}
}
完整的示例代碼,包括GetNextSiblingInVisualTree()輔助方法的代碼: https : //github.com/finnigantime/Samples/tree/master/examples/Win8Xaml/TextBox_EnterMovesFocusToNextControl
請注意,使用FocusState.Keyboard調用Focus()會在控件模板(例如Button)中顯示帶有這種矩形的元素周圍的虛線焦點。 使用FocusState.Pointer調用Focus()不會顯示焦點rect(您正在使用觸摸/鼠標,因此您知道要與哪個元素進行交互)。
我對“GetNextSiblingInVisualTree”函數稍作改進。 此版本搜索下一個TextBox而不是下一個對象。
private static DependencyObject GetNextSiblingInVisualTree(DependencyObject origin)
{
DependencyObject parent = VisualTreeHelper.GetParent(origin);
if (parent != null)
{
int childIndex = -1;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); ++i)
{
if (origin == VisualTreeHelper.GetChild(parent, i))
{
childIndex = i;
break;
}
}
for (int nextIndex = childIndex + 1; nextIndex < VisualTreeHelper.GetChildrenCount(parent); nextIndex++ )
{
DependencyObject currentObject = VisualTreeHelper.GetChild(parent, nextIndex);
if( currentObject.GetType() == typeof(TextBox))
{
return currentObject;
}
}
}
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.