It seems such a simple thing to do: use a TextBox to display some output and allow the user to cut and paste from it, scroll it but not edit it.
BUT: if a TextBox is readonly, then it loses most of its keyboard behaviour. You can click on it and select text using the invisible cursor, but it will not scroll or navigate.
I have this (terrible) solution.
<TextBox Focusable="True"
VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
FontFamily="Consolas" FontSize="10pt"
Foreground="{Binding Path=OutputTextColour}"
Text="{Binding Path=OutputText}"
Background="White" PreviewKeyDown="TextBox_PreviewKeyDown" />
And a handler to throw away any attempts to edit:
private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e) {
// the IsReadOnly flag on the control doesn't let the navigation keys work! WPF BUG?
if (!(e.Key == Key.Down || e.Key == Key.Up || e.Key == Key.Left || e.Key == Key.Right
|| e.Key == Key.Home || e.Key == Key.End || e.Key == Key.PageDown || e.Key == Key.PageUp
|| e.Key == Key.Tab || e.Key == Key.Escape))
e.Handled = true;
}
I have also tried a readonly TextBox inside a ScrollViewer, but it seems the TextBox, even when readonly, still swallows the navigation keystrokes and the ScrollView never sees them. If the ScrollViewer gets the focus then scrolling works and cut/copy/paste do not!
Yes, I could probably get all that to work by some fancy footwork with PreviewKeyDown, but really I just want a TextBox that plays nice!
The answer is to set
IsReadOnlyCaretVisible="True"
as described here:
Readonly textbox for WPF with visible cursor (.NET 3.5)
Works beautifully!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With