4

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!

david.pfx
  • 10,520
  • 3
  • 30
  • 63
  • For your current solution, what about when I want to hold down shift and select with the arrow keys, or Ctrl to select whole words? – Mathemats Jan 25 '16 at 01:30
  • What keyboard behavior is missing? I can shift and ctrl-select text...I can use arrow keys and scroll with mouse selection – Bubba Jan 25 '16 at 01:50
  • @Bubba: PgUp, PgDn, Home, End, Ctrl+Home, Ctrl+End lose their scrolling behaviour. – david.pfx Jan 25 '16 at 05:13
  • @Mathemats: they work OK. Arrow keys are not marked as handled, so get passed through. – david.pfx Jan 25 '16 at 05:14
  • I might be missing something, but your if statement reads if the key pressed is _not_ (left, up, etc) then handle it. Wouldn't you want to handle these key presses? Also, throw some braces around the body of the if... – Mathemats Jan 25 '16 at 05:20
  • @Mathemats: if the key is not left, up etc then mark it handled so it doesn't get passed through. Only allow TextBox to see these chars. [And I NEVER write unnecessary braces -- you shouldn't either.] – david.pfx Jan 25 '16 at 13:49

1 Answers1

11

The answer is to set

IsReadOnlyCaretVisible="True"

as described here:

Readonly textbox for WPF with visible cursor (.NET 3.5)

Works beautifully!

Community
  • 1
  • 1
Jim Foye
  • 1,918
  • 1
  • 13
  • 15