Home > Software design >  Set 2-Line text box
Set 2-Line text box

Time:09-17

Goal:

I'm trying to create a TextBox with space for exactly 2 lines. The content will later be filled into a document which has a maximum space for two lines.

enter image description here

The user should be able to see that visually in the application to generate the Document:

enter image description here

Current Situation / Issue

The TextBox sits in a Grid with <RowDefinition Height="auto"></RowDefinition>. This leads the Textbox to occupy exactly 1 Line of space (marked in yellow): enter image description here

Only when the first letter is beeing typed, the textbox expands to two lines due to MinLines="2". I do have the Idea to set a static height to the Grid.Row but to be honest, I really dislike static sizing and I feel that it is not the apropriate solution.

Additionally, eventhough MaxLines="2" the textbox will happily wrap around any number of lines. I have set MaxLength="200" - It kind of does the Job but has nothing to do with the actual text size.
(iiiii vs WWWWW)

Current Code:

<Grid x:Name="EigenbelegGrid">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="auto"></ColumnDefinition>
        <ColumnDefinition></ColumnDefinition>
        <ColumnDefinition Width="auto"></ColumnDefinition>
        <ColumnDefinition Width="auto"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="auto"></RowDefinition>
        <RowDefinition Height="auto"></RowDefinition>
    </Grid.RowDefinitions>
    <!-- Preset -->
    <Label Content="Preset" Grid.Column="0" Grid.Row="0"></Label>
    <ComboBox x:Name="TemplateSelection_DropDown" Grid.Column="1" Grid.Row="0" IsEditable="True"
    <Button x:Name="SavePreset_Button" Content="Save" Grid.Column="2" Grid.Row="0"></Button>
    <Button x:Name="DeletePreset_Button" Content="Delete" Grid.Column="3" Grid.Row="0"></Button>
    <!-- Reasoning -->
    <Label Content="Begründung" Grid.Column="0" Grid.Row="1"></Label>
    <TextBox x:Name="Reasoning_TextBox" Grid.Column="1" Grid.Row="1" MinLines="2" MaxLines="2" TextWrapping="Wrap" MaxLength="200"></TextBox>
</Grid>

CodePudding user response:

After being loaded to visual tree, if TextBox is blank, DesiredSize will contain the height of one line plus the height of other causes, and ExtentHeight will contain the height of one line. We can use this two to calculate the actual height we need. In your case, it will be like

<TextBox x:Name="Reasoning_TextBox" Grid.Column="1" Grid.Row="1" MaxLines="2" TextWrapping="Wrap"
         Loaded="Reasoning_TextBox_Loaded"></TextBox>

private void Reasoning_TextBox_Loaded(object sender, RoutedEventArgs e)
{
    TextBox t = (TextBox)sender;
    t.Height = t.DesiredSize.Height   t.ExtentHeight * (t.MaxLines - 1);
}
  • Related