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.
<Window
FocusManager.FocusedElement="{Binding ElementName=NumberOfDigits}"
Height="400" Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox Grid.Column="0" Grid.Row="0"
x:Name="NumberOfDigits"
IsReadOnly="{Binding Path=IsRunning, Mode=TwoWay}"
VerticalContentAlignment="Center"
Text="{Binding Path=Digits, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<Button Grid.Column="0" Grid.Row="1"
Margin="10,0,10,0"
IsDefault="True"
Content="Start"
Command="{Binding StartCommand}"/>
</Grid>
</Window>
If your textbox (WinForms) is multiline with a vertical scrollbar you can try this:
Note: In WPF .ScrollToCaret() is not a member of TextBox.
None of the answers here worked for me. I am using binding for the TextBox and needed to move the caret right after the window poped up. This did it for me:
Similar to Ceranski answer. Instead of adding to the Loaded we add to ContentRendered.
In WPF if line is long enough it is important also to scroll to the end of the line. So i'm using the following lines:
but read this caution (for me it's fine - probably already fixed): TextBox ScrollToHorizontalOffset will not scroll after text is long enough
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.
You can set the caret position using
CaretIndex
property of aTextBox
. Please bear in mind that this is not aDependencyProperty
. Nevertheless, you may still set it in XAML like this:Please remember to set
CaretIndex
afterText
property or else it will not work. Thus it probably won't work if you bind toText
like in your example. In that case, simply use code-behind like this.You may also create a Behavior, which, while still being code-behind, has the advantage of being reusable.
Example of a simple behavior class, using the focus event of the textbox:
Then, in your XAML, you attach the behavior like so: