2013-07-08 29 views
1

我想知道是否有任何方法可以獲取由TextBlock中的鼠標直接指出的字符。獲取文本塊的精確字符

我已經找到了如何使用一個TextBox使用下面的代碼來做到這一點:

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() ; 
     } 

但似乎將TextBlock沒有任何類似的方法。

有沒有人有想法?

風箏

回答

0

如果沒有現成的功能,如GetCharacterIndexFromPoint()TextBlock,我可以建議使用一個StyleTextBox,模擬TextBlock的行爲。

實施例:

<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" /> 

也許會更容易實現的功能,例如用於GetCharacterIndexFromPoint()TextBlock

+0

這是我在一段時間後想出的解決方案。所以它看起來好像沒有其他的辦法:(謝謝 –