0

I am new to both C# and XAML and I am making some sort of reading application.

So I need a TextBlock that word wraps if the title needs more than 1 row to fit. But when it becomes more that 2 rows to fit, wrap a ScrollView on it.

By doing this I could align the rest element tightly whenever it is either 1 or 2(max) row height.

How do I achieve this in XAML or C#?

J. Steen
  • 15,470
  • 15
  • 56
  • 63
user1510539
  • 581
  • 1
  • 6
  • 17

1 Answers1

0

If you can use a TextBox instead of a TextBlock, it would be easier. A TextBox supports scrolling and has a LineCount property that you can key off of. So for example, I put the a few controls into a StackPanel:

<Grid>
    <StackPanel HorizontalAlignment="Left" Height="100" Margin="105,127,0,0" VerticalAlignment="Top" Width="184">
        <TextBox Height="23" TextWrapping="Wrap" Text="TextBox" Name="TextBox1"/>
        <Button Content="Button" Click="Button_Click_2"/>
    </StackPanel>
</Grid>

Then I had some code to update the text. When I hit 2 lines, I grew the TextBox and when I got to three lines, I added scrollbars:

private void Button_Click_2(object sender, RoutedEventArgs e)
{
    TextBox1.Text += "More Text";

    if (TextBox1.LineCount >= 2)
    {
        TextBox1.Height = 38; 
    }
    if (TextBox1.LineCount >= 3)
    {
        TextBox1.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
    }
}
John Koerner
  • 37,428
  • 8
  • 84
  • 134
  • But the TextBox an input controls. How am I suppose to deal with that? – user1510539 Jan 20 '13 at 03:40
  • Depending on what you need to do, `IsReadOnly="True"` might be enough. Otherwise, there are lots of examples online on how to format a textbox in a variety of different ways. – John Koerner Jan 20 '13 at 03:46
  • So is it possible to format it exactly like TextBlock? And what about the performance? – user1510539 Jan 20 '13 at 05:17
  • @user1510539 I don't know your requirements for look and feel, but you can do all sorts of things in WPF to make a textbox look how you want. A quick google search returns [this](http://stackoverflow.com/questions/1105982/visible-line-count-of-a-textblock) and [this](http://www.stievens-corner.be/index.php/10-wpf/18-make-textbox-look-like-textblock) – John Koerner Jan 20 '13 at 12:35
  • Thanks, as a substitute. That met my requirements:) – user1510539 Jan 21 '13 at 00:23