如何在 WPF 文本框中找到插入符号的结束位置,这样我就不能再用插入符号向右移动了?
问问题
663 次
1 回答
1
如果您需要查找 CaretIndex,请查看以下问题。
但是,如果您希望在某些条件下跳转到下一个 TextBox,请查看以下示例。这里我使用 TextBox 属性 MaxLength 和 KeyUp 事件在一个完成时跳转到下一个 TextBox。
这是 XAML:
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel
Grid.Row="0">
<TextBox Text="" MaxLength="3" KeyUp="TextBox_KeyUp" >
</TextBox>
<TextBox Text="" MaxLength="3" KeyUp="TextBox_KeyUp">
</TextBox>
<TextBox Text="" MaxLength="4" KeyUp="TextBox_KeyUp">
</TextBox>
</StackPanel>
</Grid>
这是来自代码隐藏的 KeyUp 事件:
private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
TextBox tb = sender as TextBox;
if (( tb != null ) && (tb.Text.Length >= tb.MaxLength))
{
int nextIndex = 0;
var parent = VisualTreeHelper.GetParent(tb);
int items = VisualTreeHelper.GetChildrenCount(parent);
for( int index = 0; index < items; ++index )
{
TextBox child = VisualTreeHelper.GetChild(parent, index) as TextBox;
if ((child != null) && ( child == tb ))
{
nextIndex = index + 1;
if (nextIndex >= items) nextIndex = 0;
break;
}
}
TextBox nextControl = VisualTreeHelper.GetChild(parent, nextIndex) as TextBox;
if (nextControl != null)
{
nextControl.Focus();
}
}
}
编辑:
阅读以下答案 后,我修改了 TextBox_KeyUp 如下:
private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
Action<FocusNavigationDirection> moveFocus = focusDirection =>
{
e.Handled = true;
var request = new TraversalRequest(focusDirection);
var focusedElement = Keyboard.FocusedElement as UIElement;
if (focusedElement != null)
focusedElement.MoveFocus(request);
};
TextBox tb = sender as TextBox;
if ((tb != null) && (tb.Text.Length >= tb.MaxLength))
{
moveFocus(FocusNavigationDirection.Next);
}
}
}
于 2010-10-07T16:27:12.760 回答