2014-11-22 20 views
1

我基本上玩WPF文本框控件,最近打開WinForms後,我只是想知道是否有方法滾動到WPF文本框中的特定行?這怎麼能實現?WPF - 轉到文本框中的行

對於的WinForms文本框,基本上,要轉到特定行的代碼會是這樣的:

Private Sub MoveCaretToLine(txtBox As TextBox, lineNumber As Integer) 
    txtBox.HideSelection = False 
    txtBox.SelectionStart = txtBox.GetFirstCharIndexFromLine(lineNumber - 1) 
    txtBox.SelectionLength = txtBox.Lines(lineNumber - 1).Length 
    txtBox.ScrollToCaret() 
End Sub 

但我不知道我怎麼能實現它的WPF文本框?我實際上通過WinForms中的HostElement託管WPF文本框,並想知道我如何實現這一點。

+0

如果你使用FlowDocument,你可以做Run.BringIntoView但TextBox不會託管FlowDocument。 – Paparazzi 2014-11-22 17:43:01

+0

謝謝你,但我想知道我怎麼能做到這一點的WPF文本框 – Zer0 2014-11-22 19:36:19

+0

爲什麼?爲什麼不使用另一個可以滿足你需要的控件呢? – Paparazzi 2014-11-22 21:25:11

回答

1

如上所述,你發現在WPF中沒有ScrollToCaret,有一個ScrollToLine方法和一個CaretIndex方法,通過結合它們,我認爲它會按照你想要的方式工作。看看這是否適合你

Private Sub MoveCaretToLine(txtBox As TextBox, lineNumber As Integer) 
    txtBox.SelectionStart = txtBox.GetCharacterIndexFromLineIndex(lineNumber - 1) 
    txtBox.SelectionLength = txtBox.GetLineLength(lineNumber - 1) 
    txtBox.CaretIndex = txtBox.SelectionStart 
    txtBox.ScrollToLine(lineNumber - 1) 
    txtBox.Focus() 
End Sub 
+0

謝謝@Mark Hall。它的工作:D – Zer0 2014-11-23 03:32:42

+0

不客氣,很高興有幫助。 – 2014-11-23 03:33:15