如何根据UWP中的文本长度动态更改文本框宽度?

如何根据UWP中的文本长度动态更改文本框宽度?,uwp,uwp-xaml,Uwp,Uwp Xaml,我试过的是什么 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 } 我不知道,如何实

我试过的是什么

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
}

我不知道,如何实现这一点?有没有办法实现这一点?

文本框的默认行为是根据内部文本的长度更改控件的宽度

如果未明确设置
TextBox.Width
,则TextBox将在
MinWidth
MaxWidth
之间进行调整

像这样:


var-box=new TextBox();
高度=32;
box.HorizontalAlignment=HorizontalAlignment.Left;
RootGrid.Children.Add(框);
如果将文本框放置在网格中,则需要显式地将水平对齐设置为左侧


更新


如果要与当前文本宽度保持一致,也可以在不收听
TextBox.TextChanged
事件的情况下实现。我们可以尝试修改
文本框的控件模板
,以删除删除按钮


var-box=new TextBox();
高度=32;
框。填充=新厚度(0);
Style=CustomTextBoxStyle;
box.HorizontalAlignment=HorizontalAlignment.Left;
RootGrid.Children.Add(框);

对于TextBox,文本宽度不容易计算,因为无法保证内部字体为单空格字体,因此,使用控件本身的特性来实现目标是一个可行的解决方案。

是的。你说得对。但是,我想在文本更改evnt时将宽度更改为当前文本长度宽度。有什么办法吗?如果你想与当前文本宽度一致,这也可以在不收听
TextBox.TextChanged
事件的情况下实现。我们可以尝试修改
文本框的控件模板
,以删除删除按钮。我已经更新了答案,请检查。