I have a TextBlock
in WPF. I write many lines to it, far exceeding its vertical height. I expected a vertical scroll bar to appear automatically when that happens, but it didn't. I tried to look for a scroll bar property in the Properties pane, but could not find one.
How can I make vertical scroll bar created automatically for my TextBlock
once its contents exceed its height?
Clarification: I would rather do it from the designer and not by directly writing to the XAML.
Dont know if someone else has this problem but wrapping my
TextBlock
into aScrollViewer
somewhow messed up my UI - as a simple workaround I figured out that replacing theTextBlock
by aTextBox
like this onecreates a
TextBox
that looks and behaves like aTextBlock
with a scrollbar (and you can do it all in the designer).Something better would be:
This makes sure that the text in your textblock does not overflow and overlap the elements below the textblock as may be the case if you do not use the grid. That happened to me when I tried other solutions even though the textblock was already in a grid with other elements. Keep in mind that the width of the textblock should be Auto and you should specify the desired with in the Grid element. I did this in my code and it works beautifully. HTH.
can use the following now:
Wrap it in a scroll viewer:
NOTE this answer applies to a
TextBlock
(a read-only text element) as asked for in the original question.If you want to show scroll bars in a
TextBox
(an editable text element) then use theScrollViewer
attached properties:Valid values for these two properties are
Disabled
,Auto
,Hidden
andVisible
.This answer describes a solution using MVVM.
This solution is great if you want to add a logging box to a window, that automatically scrolls to the bottom each time a new logging message is added.
Once these attached properties are added, they can be reused anywhere, so it makes for very modular and reusable software.
Add this XAML:
Add this attached property:
And this attached property (to clear the box):
Then, if you're using a dependency injection framework such as MEF, you can place all of the logging-specific code into it's own ViewModel:
Here's how it works:
I am doing this in another way by putting MaxHeight in ScrollViewer.
Just Adjust the MaxHeight to show more or fewer lines of text. Easy.