我有一个TextBox,它有很多行文本,它是这样更新的:
public void UpdateMessageBox(TextBox textBox, string text)
{
textBox.SelectionStart = 0;
textBox.SelectionLength = 0;
textBox.SelectedText = String.Format("{0:HH:mm:ss }", DateTime.Now) + text + "\n";
textBox.ScrollToHome();
}
现在我需要从直接点击鼠标中键的行中获取文本,而不是先通过左键单击选择行。
private void textBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Middle && e.ButtonState == MouseButtonState.Pressed)
{
e.MouseDevice.GetPosition(textBox) //what next?
}
}
如何从鼠标位置获取textBox行及其文本?
答案 0 :(得分:3)
XAML
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBox Width="300"
Height="200"
PreviewMouseDown="TextBox_PreviewMouseDown"
Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut consectetur iaculis enim sed condimentum. Nunc vestibulum fermentum fermentum. Nam arcu ipsum, vestibulum eu felis a, varius gravida dolor. Pellentesque tempor cursus quam, mattis volutpat odio eleifend cursus. Morbi placerat auctor aliquam. Aliquam erat volutpat. Curabitur dictum convallis nibh in ullamcorper. "
TextWrapping="Wrap" />
<TextBlock x:Name="myTextBlock"
Grid.Row="1"
HorizontalAlignment="Center" />
</Grid>
代码隐藏
private void TextBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Middle)
{
var myTextBox = (TextBox)sender;
var myCharIndex = myTextBox.GetCharacterIndexFromPoint(Mouse.GetPosition(myTextBox), true);
var myLineIndex = myTextBox.GetLineIndexFromCharacterIndex(myCharIndex);
var myLine = myTextBox.GetLineText(myLineIndex);
myTextBlock.Text = myLine;
}
}