[英]How to make the StackPanel or DockPanel stretch to fit their containers in WPF?
I have a Grid
as a root container with two columns defined (There's only one row). 我有一个
Grid
作为根容器,定义了两列(只有一行)。
The first column has flexible width and second column has 300px fixed width. 第一列具有灵活的宽度,第二列具有300px的固定宽度。
Next, I have placed a ListBox
inside the second column to stretch both horizontally and vertically, ie to fill the entire second column. 接下来,我在第二列中放置了一个
ListBox
,以水平和垂直拉伸,即填充整个第二列。
Lastly, I have defined an Items Template for the ListBox
to be a vertically oriented StackPanel
, with one DockPanel
and a couple of TextBlock
s inside. 最后,我已经为
ListBox
定义了一个项目模板,它是一个垂直方向的StackPanel
,里面有一个DockPanel
和几个TextBlock
。
<!-- Data template for ListBox -->
<DataTemplate DataType="{x:Type entities:Track}">
<StackPanel Orientation="Vertical">
<DockPanel>
<TextBlock DockPanel.Dock="Left" Text="Now playing" />
<TextBlock DockPanel.Dock="Right" Text="Time remaining" />
</DockPanel>
<TextBlock Text="{Binding Artist}" />
<TextBlock Text="{Binding Title}" />
</StackPanel>
</DataTemplate>
...
<ListBox
Grid.Column="1"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" />
I have two questions: 我有两个问题:
StackPanel
fill the entire width of the ListBox
? StackPanel
填充ListBox
的整个宽度? Right now, it only takes enough space to accomodate the DockPanel
and the TextBlock
s inside. DockPanel
和TextBlock
。 It won't fit the width of the ListBox
or ListBoxItem
. ListBox
或ListBoxItem
的宽度。 DockPanel
fill the entire width of the StackPanel
, ie its parent? DockPanel
填充StackPanel
的整个宽度,即其父级? What happens right now is that even if the width of the TextBlock
s in the StackPanel
exceed the width of the DockPanel
, it won't stretch to match their width. StackPanel
TextBlock
的宽度超过DockPanel
的宽度,它也不会拉伸以匹配它们的宽度。 Thanks for the help. 谢谢您的帮助。
You can make the Content of every ListBoxItem
stretch by setting HorizontalContentAlignment
in the ItemContainerStyle 您可以通过在ItemContainerStyle中设置
HorizontalContentAlignment
来使每个ListBoxItem
拉伸的内容
<ListBox ...>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.