我想弄清楚这个问题简直要发疯了。我有一个 DockPanel,其中一些内容停靠在顶部,并以 ItemsControl 作为其中心内容(它自身显示为包含更多 DockPanel 的 WrapPanel)。
我希望中心 ItemsControl 根据需要扩展父 DockPanel 的宽度。我不希望停靠在 DockPanel 顶部的内容导致 DockPanel 展开,但我希望它使用 ItemsControl 的宽度所请求的任何空间。
下面是一些经过极大简化的 XAML,但仍然捕获了行为:
<Window x:Class="SizingTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" SizeToContent="Width" Height="150">
<Grid>
<DockPanel>
<TextBlock DockPanel.Dock="Top">Here's some really long text that should not force the window to expand. Just clip if it's wider than the buttons.</TextBlock>
<WrapPanel Orientation="Vertical">
<Button>Button 1</Button>
<Button>Button 2</Button>
<Button>Button 3</Button>
<Button>Button 4</Button>
<Button>Button 5</Button>
<Button>Button 6</Button>
<Button>Button 7</Button>
<Button>Button 8</Button>
<Button>Button 9</Button>
<Button>Button 10</Button>
</WrapPanel>
</DockPanel>
</Grid>
</Window>
换句话说,WrapPanel/DockPanel/Grid/Window 应该调整其宽度以适应 WrapPanel 的按钮列,但我希望在耗尽 WrapPanel 请求的所有可用空间后简单地剪切 TextBlock。调整窗口高度(这会导致 WrapPanel 调整自身并添加/删除列)应导致 TextBlock 更改宽度和剪辑以匹配 WrapPanel。我怎样才能做到这一点?
最佳答案
您只需要进行一些更改。首先,您需要WrapPanel
不拉伸(stretch)整个宽度
。然后,您可以将 TextBlock.Width
属性数据绑定(bind)到 WrapPanel.ActualWidth
属性。最后,您还需要将 TextBlock
上的 HorizontalAlignment
属性设置为 Left
。这应该可以解决问题:
<Grid>
<DockPanel>
<TextBlock DockPanel.Dock="Top" HorizontalAlignment="Left"
Width="{Binding ActualWidth, ElementName=Panel}" Text="Here's some really
long text that should not force the window to expand..." />
<WrapPanel Name="Panel" Orientation="Vertical" HorizontalAlignment="Left">
<Button>Button 1</Button>
<Button>Button 2</Button>
<Button>Button 3</Button>
<Button>Button 4</Button>
<Button>Button 5</Button>
<Button>Button 6</Button>
<Button>Button 7</Button>
<Button>Button 8</Button>
<Button>Button 9</Button>
<Button>Button 10</Button>
</WrapPanel>
</DockPanel>
</Grid>
最后一点是,如果您使用 TextTrimming
属性在文本末尾添加省略号 (...),就在文本被截断之前,效果会更好。你可以这样做:
<TextBlock DockPanel.Dock="Top" HorizontalAlignment="Left" Width="{Binding ActualWidth,
ElementName=Panel}" Text="Here's some really long text that should not force the
window to expand..." TextTrimming="CharacterEllipsis" />
关于wpf - 防止控件迫使 parent 调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22310378/