Created
October 11, 2013 03:11
-
-
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…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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