Search code examples
c#wpftextblock

TextBlock with a slider when text is too long in WPF


As in title. I want to create TextBlock with both horizontal and vertical sliders, that will automatically adjust depending on text size. Google just shows me Slider control which is definitely not what i'm looking for.

Any clues what can i use to achieve it?

Edit

Thanks to some of the helpful people here i have this:

        <ScrollViewer Grid.Column="1" Style="{StaticResource MaterialDesignScrollViewer}">
            <TextBlock ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Auto" Text="{Binding Path=(SQLLog:LogDisplay.LogAdvanced)}" FontSize="12"/>
        </ScrollViewer>

Vertical scroll bar appears, horizontal not. Even when text doesn't fit inside the TextBlock.


Solution

  • You can use a ScrollViewer and its HorizontalScrollBarVisiblity and VerticalScrollBarVisibility properties. Just surround your TextBox with it:

    <ScrollViewer HorizontalScrollBarVisibility="Auto" 
                  VerticalScrollBarVisibility="Auto"
                  Height="100"
                  Width="200">
        <TextBlock Text="{Binding MyFancyTextProperty}" 
                   Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ScrollViewer}}, Path=Width}"
                   TextWrapping="Wrap"/>
    </ScrollViewer>
    

    Consider adding TextWrapping="Wrap" to your TextBlock, so that its content doesn't end up being displayed in one line.

    enter image description here

    If you want to display the scrollbars at any time, even if the content fits, set their values to Visible:

    HorizontalScrollBarVisibility="Visible" 
    VerticalScrollBarVisibility="Visible"