开发者

Silverlight TextBox, moving caret position

开发者 https://www.devze.com 2022-12-15 14:49 出处:网络
I am trying to make a TextBox behavior for an on-screen keyboard, it can update the text in the textbox but I can\'t get it to focus the textbox and move the caret to the end of the text once it\'s do

I am trying to make a TextBox behavior for an on-screen keyboard, it can update the text in the textbox but I can't get it to focus the textbox and move the caret to the end of the text once it's done updating.

I have tried using TextBox.Focus() and TextBox.Select() in both开发者_开发问答 orders with no luck.

Thanks for your time


Changing the focus from within an input event handler (i.e. mouse click on a virtual key) will fail, since the mouse-up event (or key-up) will return the focus to the original element. In order to make it work, you have to dispatch the focus command to a later time using the Dispatcher object.

Example:

Dispatcher.Invoke(new Action(() =>
{
    textBox1.Focus();
    textBox1.SelectionStart = textBox1.Text.Length;
    // or textBox1.Select(textBox1.Text.Length,0);
}), System.Windows.Threading.DispatcherPriority.Background);


Here is a simple example of moving the cursor to the end of a TextBox once you have updated it.

TextBox.Focus();
TextBox.Text = "sometext ";
TextBox.SelectionStart = TextBox.Text.Length;


I had a similar situation and I attached a "TextChanged" Handler to my textbox as shown here.

<TextBox Name="tbTextEntry" Width="200" HorizontalAlignment="Center" Background="Plum" Text="{Binding Entered_text,Mode=TwoWay}" TextChanged="OnTextChanged_Handler"></TextBox>

And handled the event like this(thanks Jeff Beck from comment above):

protected void OnTextChanged_Handler(object sender, RoutedEventArgs e)
{
    TextBox my_text_box = (TextBox)sender;
    my_text_box.SelectionStart = my_text_box.Text.Length;
    Debug.WriteLine("OnTextChanged_Handler called !");
    return;
}

This is inefficient for the cases when a person leaves the onscreen keyboard and start to use the real keyboard because each new character will then cause this handler to be invoked needlessly as the cursor works just fine with real keyboard. Any more efficient solution welcome !

Hope that helps. Thanks.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号