如何将 TextBox 控件配置为当文本不再适合一行时自动调整自身垂直大小?
如何配置 TextBox
控件,使其在文本不再适合一行时自动垂直调整自身大小?
例如,在以下 XAML 中:
<DockPanel LastChildFill="True" Margin="0,0,0,0">
<Border Name="dataGridHeader"
DataContext="{Binding Descriptor.Filter}"
DockPanel.Dock="Top"
BorderThickness="1"
Style="{StaticResource ChamelionBorder}">
<Border
Padding="5"
BorderThickness="1,1,0,0"
BorderBrush="{DynamicResource {ComponentResourceKey TypeInTargetAssembly=dc:NavigationPane,
ResourceId={x:Static dc:NavigationPaneColors.NavPaneTitleBorder}}}">
<StackPanel Orientation="Horizontal">
<TextBlock
Name="DataGridTitle"
FontSize="14"
FontWeight="Bold"
Foreground="{DynamicResource {ComponentResourceKey
TypeInTargetAssembly=dc:NavigationPane,
ResourceId={x:Static dc:NavigationPaneColors.NavPaneTitleForeground}}}"/>
<StackPanel Margin="5,0" Orientation="Horizontal"
Visibility="{Binding IsFilterEnabled, FallbackValue=Collapsed, Mode=OneWay, Converter={StaticResource BooleanToVisibility}}"
IsEnabled="{Binding IsFilterEnabled, FallbackValue=false}" >
<TextBlock />
<TextBox
Name="VerticallyExpandMe"
Padding="0, 0, 0, 0"
Margin="10,2,10,-1"
AcceptsReturn="True"
VerticalAlignment="Center"
Text="{Binding QueryString}"
Foreground="{DynamicResource {ComponentResourceKey
TypeInTargetAssembly=dc:NavigationPane,
ResourceId={x:Static dc:NavigationPaneColors.NavPaneTitleForeground}}}">
</TextBox>
</StackPanel>
</StackPanel>
</Border>
</Border>
</DockPanel>
名为“VerticallyExpandMe”的 TextBox
控件需要在绑定到该控件的文本无法在一行中容纳时自动垂直扩展。当 AcceptsReturn
设置为 true 时,如果我在 TextBox
中按 Enter 键,它会垂直展开,但我希望它自动执行此操作。
How do I configure a TextBox
control to automatically resize itself vertically when text no longer fits on one line?
For example, in the following XAML:
<DockPanel LastChildFill="True" Margin="0,0,0,0">
<Border Name="dataGridHeader"
DataContext="{Binding Descriptor.Filter}"
DockPanel.Dock="Top"
BorderThickness="1"
Style="{StaticResource ChamelionBorder}">
<Border
Padding="5"
BorderThickness="1,1,0,0"
BorderBrush="{DynamicResource {ComponentResourceKey TypeInTargetAssembly=dc:NavigationPane,
ResourceId={x:Static dc:NavigationPaneColors.NavPaneTitleBorder}}}">
<StackPanel Orientation="Horizontal">
<TextBlock
Name="DataGridTitle"
FontSize="14"
FontWeight="Bold"
Foreground="{DynamicResource {ComponentResourceKey
TypeInTargetAssembly=dc:NavigationPane,
ResourceId={x:Static dc:NavigationPaneColors.NavPaneTitleForeground}}}"/>
<StackPanel Margin="5,0" Orientation="Horizontal"
Visibility="{Binding IsFilterEnabled, FallbackValue=Collapsed, Mode=OneWay, Converter={StaticResource BooleanToVisibility}}"
IsEnabled="{Binding IsFilterEnabled, FallbackValue=false}" >
<TextBlock />
<TextBox
Name="VerticallyExpandMe"
Padding="0, 0, 0, 0"
Margin="10,2,10,-1"
AcceptsReturn="True"
VerticalAlignment="Center"
Text="{Binding QueryString}"
Foreground="{DynamicResource {ComponentResourceKey
TypeInTargetAssembly=dc:NavigationPane,
ResourceId={x:Static dc:NavigationPaneColors.NavPaneTitleForeground}}}">
</TextBox>
</StackPanel>
</StackPanel>
</Border>
</Border>
</DockPanel>
The TextBox
control named "VerticallyExpandMe" needs to automatically expand vertically when the text bound to it does not fit on one line. With AcceptsReturn
set to true, TextBox
expands vertically if I press enter within it, but I want it do do this automatically.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
虽然 Andre Luus 的建议基本上是正确的,但它实际上在这里不起作用,因为你的布局会破坏文本换行。我会解释原因。
从根本上来说,问题是这样的:文本换行仅在元素的宽度受到约束时才执行任何操作,但您的
TextBox
具有不受约束的宽度,因为它是水平StackPanel
的后代。 (嗯,两个水平堆栈面板。可能更多,具体取决于您获取示例的上下文。)由于宽度不受限制,因此TextBox
不知道何时开始换行,并且所以即使您启用了换行,它也永远不会换行。您需要做两件事:限制其宽度并启用环绕。这是更详细的解释。
您的示例包含许多与问题无关的细节。这是我稍微删减的版本,以便更容易解释问题所在:
因此,我删除了包含的
DockPanel
以及其中的两个嵌套Border
元素,因为它们既不是问题的一部分,也与解决方案无关。因此,我从示例中的一对嵌套StackPanel
元素开始。我还删除了大部分属性,因为它们中的大多数也与布局无关。这看起来有点奇怪 - 有两个像这样的嵌套水平堆栈面板看起来多余,但如果您需要使嵌套面板在运行时可见或不可见,那么它在原始版本中实际上是有意义的。但它让我们更容易看到问题。
(空的
TextBlock
标记也很奇怪,但这与原始内容中显示的完全一样。这似乎没有做任何有用的事情。)问题是:您的
TextBox 位于一些水平
StackPanel
元素内,这意味着它的宽度不受限制 - 您无意中告诉文本框它可以自由增长到任何宽度,无论实际可用空间有多少。StackPanel 将始终执行在堆叠方向上不受约束的布局。因此,在布局
TextBox
时,它会将double.PositiveInfinity
的水平尺寸传递给TextBox
。所以TextBox
总是认为它的空间比它需要的多。此外,当 StackPanel 的子级请求比实际可用空间更多的空间时,StackPanel 就会撒谎,假装给它那么多空间,然后裁剪它。(这是您为
StackPanel
的极端简单性付出的代价 - 它简单到了愚蠢的地步,因为它会很乐意构造实际上不适合的布局。您应该只使用 < code>StackPanel 如果您确实有无限的空间,因为您位于 ScrollViewer 内,或者您确定您的项目足够少,不会用完空间,或者如果您不关心项目在变得太大时从面板末端跑出,并且您不希望布局系统尝试做任何比简单地裁剪内容更聪明的事情。)因此打开文本换行在这里没有帮助,因为 StackPanel 总是假装有足够的空间来容纳文本。
您需要不同的布局结构。使用堆栈面板是错误的,因为它们不会强加您需要进行文本换行的布局约束。
这是一个简单的示例,大致可以满足您的要求:
如果您创建一个全新的 WPF 应用程序并将其粘贴为主窗口的内容,您应该会发现它执行您想要的操作 -
TextBox
开始时一行高,填充可用宽度,如果您输入文本,它会在以下位置增长一行当您添加更多文本时。当然,布局行为始终对上下文敏感,因此仅将其放入现有应用程序的中间可能还不够。如果粘贴到固定大小的空间(例如作为窗口的主体)中,这将起作用,但如果将其粘贴到宽度不受限制的上下文中,则将无法正常工作。 (例如,在
ScrollViewer
内,或在水平StackPanel
内。)因此,如果这对您不起作用,则可能是因为您的其他地方出现了其他问题。布局 - 其他地方可能还有更多
StackPanel
元素。从您的示例来看,可能值得花一些时间思考布局中真正需要的内容并简化它 - 负边距的存在,以及似乎没有执行任何类似空TextBlock< 之类的操作的元素/code> 通常表示布局过于复杂。布局中不必要的复杂性使得实现您想要的效果变得非常困难。
Although Andre Luus's suggestion is basically correct, it won't actually work here, because your layout will defeat text wrapping. I'll explain why.
Fundamentally, the problem is this: text wrapping only does anything when an element's width is constrained, but your
TextBox
has unconstrained width because it's a descendant of a horizontalStackPanel
. (Well, two horizontal stack panels. Possibly more, depending on the context from which you took your example.) Since the width is unconstrained, theTextBox
has no idea when it is supposed to start wrapping, and so it will never wrap, even if you enable wrapping. You need to do two things: constrain its width and enable wrapping.Here's a more detailed explanation.
Your example contains a lot of detail irrelevant to the problem. Here's a version I've trimmed down somewhat to make it easier to explain what's wrong:
So I've removed your containing
DockPanel
and the two nestedBorder
elements inside of that, because they're neither part of the problem nor relevant to the solution. So I'm starting at the pair of nestedStackPanel
elements in your example. And I've also removed most of the attributes because most of them are also not relevant to the layout.This looks a bit weird - having two nested horizontal stack panels like this looks redundant, but it does actually make sense in your original if you need to make the nested one visible or invisible at runtime. But it makes it easier to see the problem.
(The empty
TextBlock
tag is also weird, but that's exactly as it appears in your original. That doesn't appear to be doing anything useful.)And here's the problem: your
TextBox
is inside some horizontalStackPanel
elements, meaning its width is unconstrained - you have inadvertently told the text box that it is free to grow to any width, regardless of how much space is actually available.A
StackPanel
will always perform layout that is unconstrained in the direction of stacking. So when it comes to lay out thatTextBox
, it'll pass in a horizontal size ofdouble.PositiveInfinity
to theTextBox
. So theTextBox
will always think it has more space than it needs. Moreover, when a child of aStackPanel
asks for more space than is actually available, theStackPanel
lies, and pretends to give it that much space, but then crops it.(This is the price you pay for the extreme simplicity of
StackPanel
- it's simple to the point of being bone-headed, because it will happily construct layouts that don't actually fit. You should only useStackPanel
if either you really do have unlimited space because you're inside aScrollViewer
, or you are certain that you have sufficiently few items that you're not going to run out of space, or if you don't care about items running off the end of the panel when they get too large and you don't want the layout system to try to do anything more clever than simply cropping the content.)So turning on text wrapping won't help here, because the
StackPanel
will always pretend that there's more than enough space for the text.You need a different layout structure. Stack panels are the wrong thing to use because they will not impose the layout constraint you need to get text wrapping to kick in.
Here's a simple example that does roughly what you want:
If you create a brand new WPF application and paste that in as the content of the main window, you should find it does what you want - the
TextBox
starts out one line tall, fills the available width, and if you type text in, it'll grow one line at a time as you add more text.Of course, layout behaviour is always sensitive to context, so it may not be enough to just throw that into the middle of your existing application. That will work if pasted into a fixed-size space (e.g. as the body of a window), but will not work correctly if you paste it into a context where width is unconstrained. (E.g., inside a
ScrollViewer
, or inside a horizontalStackPanel
.)So if this doesn't work for you, it'll be because of other things wrong elsewhere in your layout - possibly yet more
StackPanel
elements elsewhere. From the look of your example, it's probably worth spending some time thinking about what you really need in your layout and simplifying it - the presence of negative margins, and elements that don't appear to do anything like that emptyTextBlock
are usually indicative of an over-complicated layout. And unnecessary complexity in a layout makes it much hard to achieve the effects you're looking for.或者,您可以通过将
TextBlock
的Width
绑定到父级的ActualWidth
来约束它,例如:这将强制它调整其高度大小也自动。
Alternatively, you could constrain your
TextBlock
'sWidth
by binding it to a parent'sActualWidth
, for example:This will force it to resize its height automatically too.
使用
MaxWidth
和TextWrapping="WrapWithOverflow"
。Use
MaxWidth
andTextWrapping="WrapWithOverflow"
.我正在使用另一种简单的方法,该方法允许我不更改文档布局。
主要思想是不要在控件开始更改之前设置宽度。对于
TextBox
es,我处理SizeChanged
事件:I'm using another simple approach that allows me not to change the document layout.
The main idea is not to set the control
Width
before it starts changing. ForTextBox
es, I handle theSizeChanged
event:您可以使用扩展 TextBlock 的此类。它会自动缩小并考虑 MaxHeight / MaxWidth:
You can use this class which extends TextBlock. It does auto-shrinking and takes MaxHeight / MaxWidth into consideration: