如何根据输入扩展/调整xaml文本框的大小?

时间:2015-09-07 09:55:39

标签: wpf xaml c#-4.0 wpf-controls

<Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <TextBlock Text="Name:" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="5"/>
            <TextBox Grid.Column="1" x:Name="txtName" Text="{Binding InName, Mode=TwoWay}" Margin="0 5" Width="200"/>
            <TextBlock Text="Type:" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,4,10,6" Grid.Row="1"/>
            <ComboBox Grid.Column="1" x:Name="cmbInsuredType" Text="{Binding InType, Mode=OneWayToSource}" Margin="35,4,165,0" Width="200" Grid.ColumnSpan="3" Grid.Row="1"/>
            <TextBlock Grid.Row="1" Text="Active:" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,36,11,-26"/>
            <CheckBox Grid.Row="1" x:Name="chkIsActive" Grid.Column="1" IsChecked="{Binding Active, Mode=OneWayToSource}" VerticalAlignment="Center" Grid.ColumnSpan="2" Margin="35,39,45,-26" />
        </Grid>

我想根据输入的用户输入水平而不是垂直地调整名称xaml文本框控件(增长/缩小)。请帮助

2 个答案:

答案 0 :(得分:1)

删除文本框上的宽度,并在文本框

上设置Horizo​​ntalAlignment =“Stretch”

答案 1 :(得分:0)

您可以从以下代码开始:

<TextBox Height="20" TextChanged="TextBox_TextChanged" MinWidth="50" Padding="0" />

在您的代码中

private Size MeasureString(string candidate, TextBox tb)
{
  var formattedText = new FormattedText(
      candidate, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface(tb.FontFamily, tb.FontStyle, tb.FontWeight, tb.FontStretch), tb.FontSize, Brushes.Black);

  return new Size(formattedText.Width, formattedText.Height);
}

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
  if (sender is TextBox)
    ((TextBox)sender).Width = MeasureString(((TextBox)sender).Text, (TextBox)sender).Width;
}