Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Created October 11, 2013 03:11
Show Gist options
  • Save primaryobjects/6929031 to your computer and use it in GitHub Desktop.
Save primaryobjects/6929031 to your computer and use it in GitHub Desktop.
Auto-sizing a window by height, based on the text contents of a TextBlock in WPF C#. Normally, wrapping a TextBlock in a ScrollViewer will show a vertical scrollbar if the text is too tall for the TextBlock. This handy code automatically resizes the TextBlock and Window height to compensate for the text, so the vertical scrollbar, hopefully, doe…
<ScrollViewer Margin="2,34,0,0" Grid.RowSpan="2" Name="scrollViewer" VerticalScrollBarVisibility="Auto">
<TextBlock Grid.Row="1" x:Name="tbMessage" TextWrapping="Wrap" Text="A long block of overflowing text goes here." />
</ScrollViewer>
private void OnLoaded(object sender, RoutedEventArgs e)
{
// Adjust height of window to match text height. Scroll bars shouldn't show.
if (scrollViewer.ComputedVerticalScrollBarVisibility == System.Windows.Visibility.Visible)
{
scrollViewer.Height += scrollViewer.ScrollableHeight;
Height += scrollViewer.ScrollableHeight;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment