【问题标题】:Set 2-Line text box设置 2 行文本框
【发布时间】:2021-08-27 09:17:41
【问题描述】:

目标:

我正在尝试创建一个文本框,其空间正好为 2 行。 内容稍后将被填充到一个最大空间为两行的文档中。

用户应该能够在应用程序中直观地看到它以生成文档:

现状/问题

TextBox 与<RowDefinition Height="auto"></RowDefinition> 位于一个网格中。这导致文本框恰好占据 1 行空间(标记为黄色):

只有在输入第一个字母时,由于MinLines="2",文本框才会扩展为两行。我确实有为 Grid.Row 设置静态高度的想法,但老实说,我真的不喜欢静态大小,我觉得这不是合适的解决方案。

此外,尽管MaxLines="2" 文本框会很高兴地环绕任意数量的行。 我设置了MaxLength="200" - 它有点像工作,但与实际文本大小无关。
(iii 与 WWWWW)

当前代码:

<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>

【问题讨论】:

  • 这能回答你的问题吗? MinLines and MaxLines on TextBox not working
  • 您可以在 TextChanged 事件中读取 TextBox 的 LineCount 属性
  • 或者您可以只使用两个文本框,这会让您更轻松。它还允许用户查看哪些文本显示在哪一行。
  • @PalleDue 谢谢你的建议。这是一种解决方法。
  • @julianbechtold:是的,这是一种解决方法,但似乎没有任何好的、有效的解决方案。

标签: c# wpf xaml textbox


【解决方案1】:

加载到可视化树后,如果TextBox为空,DesiredSize将包含一行的高度加上其他原因的高度,ExtentHeight将包含一行的高度。我们可以使用这两个来计算我们需要的实际高度。在你的情况下,它会像

<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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    相关资源
    最近更新 更多