tags:

views:

52

answers:

2

I have a TextBlock that presents a text. When the user clicks on the text, it is dynamically replaced with a TextBox (which is binded to the same data), effectively switching into "edit mode". This also significantly improves the performance.

The only caveat is that I am not able to know which part of the text the user clicked on. Therefore, the cursor always appears at the first position on the TextBox. Ideally, the cursor should appear in the same text position that the user clicked on.

+1  A: 

Try this:

  1. Create a TextBox
  2. Create a Style named LockedTextBoxStyle
    • BorderThickness: 0
    • IsReadOnly: True
    • IsReadOnlyCaretVisible: True
    • Cursor: Arrow
  3. Create a trigger for IsKeyboardFocused When true set the style to LockedTextBoxStyle

Since IsReadOnlyCaretVisible is set to true, I hope that would preserve the caret position. Haven't tested yet.

Veer
@Veer yout solution works well, but it requires using a `TextBox` and not a `TextBlock` in the read only mode and therefore loose the performance gains.If I won't find another way, your solution is a great alternative, thanks.By the way, `TextBox.IsReadOnlyCaretVisible` is a .Net 4.0 feature.
Elad
@Elad: Don't know what kind of performance you gain using a `TextBlock`. Might be you're using numerous TextBlocks.
Veer
A: 

Apperantly, The solution is quite simple and straightforward. However, It still uses TextBox and not TextBlock. The following method receives MouseButtonEventArgs from a mouse click event and the TextBox that triggered the event and return the text index on which the user clicked.

private int GetMouseClickPosition(MouseButtonEventArgs mouseButtonEventArgs, 
                                  TextBox textBox1)
    {
        Point mouseDownPoint = mouseButtonEventArgs.GetPosition(textBox1);
        return textBox1.GetCharacterIndexFromPoint(mouseDownPoint, true);
    }
Elad