Setting the CaretPosition in a RichTextBox Control does not correctly initialize the internal TextEditor's state
- Dominant language
- C#
- Stars
- 7.7k
- Forks
- 1.3k
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 61
Description
### Description
When you set the CaretPosition property of a RichTextBox programmatically that contains wrapped text, subsequent keyboard movements to the next or previous "line" don't behave correctly.
This is due to the internal TextEditor's _suggestedX member not being cleared correctly (it has the default value 0 and should be double.NaN so that internal keyboard navigations (e.g. by "OnMoveDownByLine(...)") are handled correctly. This is because the GetSuggestedX method requires the current value to be set to double.NaN in order to re-calculate the value correctly.
I wonder if "TextEditorSelection.ClearSuggestedX(TextEditor)" needs to be called automatically whenever the CaretPosition setter is used.
### Reproduction Steps
Build a WPF Application (I used .NET 8):
```
```
```
using System.Windows;
namespace RTB_SuggestX_Issue
{
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
rtb.Focus();
rtb.CaretPosition = rtb.GetPositionFromPoint(new Point(100, 0), true);
}
}
}
```
1. Click the Button
2. Press the ArrowKey Down next and observe that the caret is placed at position 0 instead of 100
Note that this problem also persists in other scenarios, e.g:
1. Restart the application
2. Click the button
3. Press the ArrowKey Down next and observe that the caret is placed at position 0 instead of 100
4. Move the Caret left or right with the arrow keys (but stay in the second line)
5. Click the button again
6. Press the ArrowKey Down abd observe that the cache seems to have been cleared correctly for this movement
7. move the caret left/right again with the arrow keys (but stay in the second line), remember this position, make it different from the starting position
8. Click the button again
9. Press the ArrowKey Down and observe that the caret is placed at the position of step 7
### Expected behavior
The caret always behaves correctly, even if the CaretPosition was set programmatically.
### Actual behavior
See reproduction section.
### Regression?
I never experienced this to work before, but I also never tried it before.
### Known Workarounds
Use reflection to call TextEditorSelection.ClearSuggestedX(TextEditor) after setting the CaretPosition.
### Impact
I cannot build keyboard navigation between different TextBoxBase controls without the mentioned workaround.
### Configuration
.NET 8
Windows 11
x64
I don't think it is specific to any configuration.
### Other information
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.