这本应该是一个很简单的方法,但我仍然无法理解。
在我的示例应用程序中, 按钮 和A 文本框 在一个 坞面板 . 如果文本框的内容小于文本框的内容,则窗口的大小与显示按钮内容所需的大小相同。这就是我想要的。但是如果我在文本框中放入更多的文本,窗口就会变宽:-(
我想要的行为是,窗口根据按钮内容获取宽度,文本框包装其内容(或/并在必要时显示滚动条)。
谢谢您!
一些示例代码:
<Window x:Class="SO1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" SizeToContent="Width" FontSize="20"> <DockPanel> <Button DockPanel.Dock="Top">A rather long text</Button> <TextBlock TextWrapping="Wrap">Short text</TextBlock> </DockPanel> </Window>
尝试过之后,似乎 TextBlock 的 MaxWidth 到 ActualWidth 的 Button 达到你想要的效果:
TextBlock
MaxWidth
ActualWidth
Button
<Button x:Name="btn" DockPanel.Dock="Top">Short text</Button> <TextBlock TextWrapping="Wrap" MaxWidth="{Binding ElementName=btn,Path=ActualWidth}">A rather long text</TextBlock>