如何捕获文本框中的光标位置?

时间:2017-09-05 20:43:00

标签: c# wpf xaml events textbox

我的Masked TextBox上有一个TextChanged事件,我希望在光标停留在最后时调用它的方法。

例如:

222.222.2 / 21

一旦用户键入" 1"就会调用该事件。

XAML

<TextBox
                Name="myTextBox"
                ToolTip="type here"
                Height="30"
                Width="100"
                FontSize="14"
                MaxLength="12"
                HorizontalContentAlignment="Right"
                TextChanged="MyMethod"/>

C#

 private void MyMethod(object sender, EventArgs e){
     if (myTextBox.Text.Length == myTextBox.MaxLength)
        {
            //how do I know if the cursor is at the end?
        }
    }

private void MyMethod(object sender, EventArgs e){
     if (myTextBox.Text.Length == myTextBox.MaxLength)
        {
            if(process.CaretIndex == 12)
            {
               //do something
            }
        }
    }

1 个答案:

答案 0 :(得分:6)

您可以使用myTextBox.CaretIndex

private void MyMethod(object sender, EventArgs e)
{
    if (myTextBox.Text.Length == myTextBox.MaxLength)
    {
        System.Diagnostics.Debug.WriteLine($"caret is at {myTextBox.CaretIndex}");
    }
}