Set the caret/cursor position to the end of the string value WPF textbox
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am try to set the caret/cursor position to the end of the string value in my WPF textbox when I open my window for the first time. I use the FocusManager to set the focus on my textbox when my window opens.
Nothing seems to work. Any ideas?
Note, I am using the MVVM pattern, and I included only a portion of the XAML from my code.
回答1:
You can set the caret position using CaretIndex property of a TextBox. Please bear in mind that this is not a DependencyProperty. Nevertheless, you may still set it in XAML like this:
Please remember to set CaretIndexafterText property or else it will not work. Thus it probably won't work if you bind to Text like in your example. In that case, simply use code-behind like this.
Note: In WPF .ScrollToCaret() is not a member of TextBox.
回答4:
This worked for me. I am also using the MVVM pattern. However, my purpose for using a MMVM is to make unit testing possible and to make it easier to update my UI (loosely coupled). I don't see myself unit testing the position of the cursor so I don't mind resorting to the code behind for this simple task.