Search code examples
wpfxamlmousetextblock

Get a precise character of a textblock


I would like to know if there were any way to get the character which is directly pointed out by the mouse in a TextBlock.

I've found how to do this using a TextBox by using the following code :

 private void TextBox_MouseMove(object sender, MouseEventArgs e)
        {
            TextBox t = sender as TextBox;
            Point p = e.GetPosition(t);

            int val =  t.GetCharacterIndexFromPoint(p, true);    

            txtResult.Text = t.Text[val].ToString() ;
        }

but it seems that the TextBlock doesn't have any similar method.

Does anyone have an idea?

KiTe


Solution

  • If there is no ready-made features such as GetCharacterIndexFromPoint() for TextBlock, I can advise to use a Style for TextBox that simulates the behavior of the TextBlock.

    Example:

    <Style x:Key="TextBlockBehavior" TargetType="{x:Type TextBox}">
        <Setter Property="IsReadOnly" Value="True" />
        <Setter Property="BorderThickness" Value="0" />
        <Setter Property="Padding" Value="0" />
        <Setter Property="BorderBrush" Value="Transparent" />
        <Setter Property="Cursor" Value="Arrow" />
    </Style>
    
    <TextBox Style="{StaticResource TextBlockBehavior}" Text="Sample" Width="100" Height="30" MouseMove="TextBox_MouseMove" />
    

    Perhaps it will be easier to implement functions such as GetCharacterIndexFromPoint() for TextBlock.