【问题标题】:how to change the TextBox width dynamically based on text length in UWP?如何根据 UWP 中的文本长度动态更改 TextBox 宽度?
【发布时间】:2021-02-02 22:36:44
【问题描述】:

我试过的是什么?

TextBox box=new TextBox{Height=32};
box.TextChanged += TextChanged;
private void TextChanged(object sender, TextChangedEventArgs e)
{
   //whenever the textbox text changed,i want to set the width of textbox to current text lenght
}

我不知道,如何实现?有什么方法可以实现吗?

【问题讨论】:

    标签: uwp uwp-xaml


    【解决方案1】:

    TextBox的默认行为是根据内部文本的长度改变控件的宽度。

    如果TextBox.Width没有显式设置,那么TextBox会在MinWidthMaxWidth之间调整。

    像这样:

    <Grid x:Name="RootGrid">
    </Grid>
    
    var box = new TextBox();
    box.Height = 32;
    box.HorizontalAlignment = HorizontalAlignment.Left;
    RootGrid.Children.Add(box);
    

    如果将TextBox放在Grid中,则需要显式设置Horizo​​ntalAlignment为Left


    更新

    如果你想和当前的文字宽度保持一致,这也可以不用监听TextBox.TextChanged事件来实现。我们可以尝试修改TextBox的控件模板,去掉删除按钮。

    <Style TargetType="TextBox" x:Name="CustomTextBoxStyle">
        <Setter Property="Foreground" Value="{ThemeResource TextControlForeground}" />
        <Setter Property="Background" Value="{ThemeResource TextControlBackground}" />
        <Setter Property="BorderBrush" Value="{ThemeResource TextControlBorderBrush}" />
        <Setter Property="SelectionHighlightColor" Value="{ThemeResource TextControlSelectionHighlightColor}" />
        <Setter Property="BorderThickness" Value="{ThemeResource TextControlBorderThemeThickness}" />
        <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}" />
        <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}" />
        <Setter Property="ScrollViewer.HorizontalScrollMode" Value="Auto" />
        <Setter Property="ScrollViewer.VerticalScrollMode" Value="Auto" />
        <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Hidden" />
        <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Hidden" />
        <Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="False" />
        <Setter Property="Padding" Value="{ThemeResource TextControlThemePadding}" />
        <Setter Property="UseSystemFocusVisuals" Value="{ThemeResource IsApplicationFocusVisualKindReveal}" />
        <Setter Property="ContextFlyout" Value="{StaticResource TextControlCommandBarContextFlyout}" />
        <Setter Property="SelectionFlyout" Value="{StaticResource TextControlCommandBarSelectionFlyout}" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="TextBox">
                    <Grid>
    
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                        <VisualState x:Name="Normal" />
    
                                        <VisualState x:Name="Disabled">
    
                                            <Storyboard>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="HeaderContentPresenter" Storyboard.TargetProperty="Foreground">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlHeaderForegroundDisabled}" />
                                                </ObjectAnimationUsingKeyFrames>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="Background">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundDisabled}" />
                                                </ObjectAnimationUsingKeyFrames>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushDisabled}" />
                                                </ObjectAnimationUsingKeyFrames>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundDisabled}" />
                                                </ObjectAnimationUsingKeyFrames>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="PlaceholderTextContentPresenter" Storyboard.TargetProperty="Foreground">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{Binding PlaceholderForeground, RelativeSource={RelativeSource TemplatedParent}, TargetNullValue={ThemeResource TextControlPlaceholderForegroundDisabled}}" />
                                                </ObjectAnimationUsingKeyFrames>
                                            </Storyboard>
                                        </VisualState>
    
                                        <VisualState x:Name="PointerOver">
    
                                            <Storyboard>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushPointerOver}" />
                                                </ObjectAnimationUsingKeyFrames>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="Background">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundPointerOver}" />
                                                </ObjectAnimationUsingKeyFrames>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="PlaceholderTextContentPresenter" Storyboard.TargetProperty="Foreground">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{Binding PlaceholderForeground, RelativeSource={RelativeSource TemplatedParent}, TargetNullValue={ThemeResource TextControlPlaceholderForegroundPointerOver}}" />
                                                </ObjectAnimationUsingKeyFrames>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundPointerOver}" />
                                                </ObjectAnimationUsingKeyFrames>
                                            </Storyboard>
                                        </VisualState>
                                        <VisualState x:Name="Focused">
    
                                            <Storyboard>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="PlaceholderTextContentPresenter" Storyboard.TargetProperty="Foreground">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{Binding PlaceholderForeground, RelativeSource={RelativeSource TemplatedParent}, TargetNullValue={ThemeResource TextControlPlaceholderForegroundFocused}}" />
                                                </ObjectAnimationUsingKeyFrames>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="Background">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundFocused}" />
                                                </ObjectAnimationUsingKeyFrames>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushFocused}" />
                                                </ObjectAnimationUsingKeyFrames>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundFocused}" />
                                                </ObjectAnimationUsingKeyFrames>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="RequestedTheme">
                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="Light" />
                                                </ObjectAnimationUsingKeyFrames>
                                            </Storyboard>
                                        </VisualState>
    
                                    </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
    
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="*" />
                            <RowDefinition Height="Auto" />
                        </Grid.RowDefinitions>
    
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>
    
                        <ContentPresenter x:Name="HeaderContentPresenter"
                        Grid.Row="0"
                        Grid.Column="0"
                        Grid.ColumnSpan="2"
                        Content="{TemplateBinding Header}"
                        ContentTemplate="{TemplateBinding HeaderTemplate}"
                        FontWeight="Normal"
                        Foreground="{ThemeResource TextControlHeaderForeground}"
                        Margin="{ThemeResource TextBoxTopHeaderMargin}"
                        TextWrapping="Wrap"
                        VerticalAlignment="Top"
                        Visibility="Collapsed"
                        x:DeferLoadStrategy="Lazy" />
                        <Border x:Name="BorderElement"
                        Grid.Row="1"
                        Grid.Column="0"
                        Grid.RowSpan="1"
                        Grid.ColumnSpan="2"
                        Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        CornerRadius="{TemplateBinding CornerRadius}"
                        Control.IsTemplateFocusTarget="True"
                        MinWidth="{ThemeResource TextControlThemeMinWidth}"
                        MinHeight="{ThemeResource TextControlThemeMinHeight}" />
                        <ScrollViewer x:Name="ContentElement"
                        Grid.Row="1"
                        Grid.Column="0"
                        HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}"
                        HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}"
                        VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}"
                        VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}"
                        IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}"
                        IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}"
                        IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}"
                        Margin="{TemplateBinding BorderThickness}"
                        Padding="{TemplateBinding Padding}" VerticalAlignment="Center"
                        IsTabStop="False"
                        AutomationProperties.AccessibilityView="Raw"
                        ZoomMode="Disabled" />
                        <TextBlock x:Name="PlaceholderTextContentPresenter"
                        Grid.Row="1"
                        Grid.Column="0"
                        Grid.ColumnSpan="2"
                        Foreground="{Binding PlaceholderForeground, RelativeSource={RelativeSource TemplatedParent}, TargetNullValue={ThemeResource TextControlPlaceholderForeground}}"
                        Margin="{TemplateBinding BorderThickness}"
                        Padding="{TemplateBinding Padding}"
                        Text="{TemplateBinding PlaceholderText}"
                        TextAlignment="{TemplateBinding TextAlignment}"
                        TextWrapping="{TemplateBinding TextWrapping}"
                        IsHitTestVisible="False" />
                        <ContentPresenter x:Name="DescriptionPresenter"
                        Grid.Row="2"
                        Grid.Column="0"
                        Grid.ColumnSpan="2"
                        Content="{TemplateBinding Description}"
                        Foreground="{ThemeResource SystemControlDescriptionTextForegroundBrush}"
                        AutomationProperties.AccessibilityView="Raw"
                        x:Load="False"/>
    
                    </Grid>
    
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    
    var box = new TextBox();
    box.Height = 32;
    box.Padding = new Thickness(0);
    box.Style = CustomTextBoxStyle;
    box.HorizontalAlignment = HorizontalAlignment.Left;
    RootGrid.Children.Add(box);
    

    对于TextBox来说,文字宽度不好计算,因为内部字体不能保证是等宽字体,所以利用控件本身的特性来达到目的是一种可行的方案。

    【讨论】:

    • 是的。你是对的。但是我想在文本更改时将宽度更改为当前文本长度宽度。有什么办法吗?
    • 如果想和当前的文字宽度保持一致,这个也可以不用监听TextBox.TextChanged事件来实现。我们可以尝试修改TextBox的控件模板,去掉删除按钮。我已经更新了答案,请检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    相关资源
    最近更新 更多