如何使 StackPanel 或 DockPanel 拉伸以适应 WPF 中的容器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5079571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make the StackPanel or DockPanel stretch to fit their containers in WPF?
提问by Boris
I have a Grid
as a root container with two columns defined (There's only one row).
The first column has flexible width and second column has 300px fixed width.
Next, I have placed a ListBox
inside the second column to stretch both horizontally and vertically, i.e. to fill the entire second column.
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.
我有一个Grid
定义了两列的根容器(只有一行)。
第一列具有灵活的宽度,第二列具有 300px 的固定宽度。
接下来,我ListBox
在第二列内放置了一个以水平和垂直拉伸,即填充整个第二列。
最后,我定义了ListBox
一个垂直方向的 Items 模板StackPanel
,里面有一个DockPanel
和几个TextBlock
s。
<!-- 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:
我有两个问题:
- How do I make the
StackPanel
fill the entire width of theListBox
? Right now, it only takes enough space to accomodate theDockPanel
and theTextBlock
s inside. It won't fit the width of theListBox
orListBoxItem
. - Next, how do I make the
DockPanel
fill the entire width of theStackPanel
, i.e. its parent? What happens right now is that even if the width of theTextBlock
s in theStackPanel
exceed the width of theDockPanel
, it won't stretch to match their width.
- 如何
StackPanel
填充整个宽度ListBox
?现在,它只需要足够的空间来容纳里面的DockPanel
和TextBlock
s。它不适合ListBox
or的宽度ListBoxItem
。 - 接下来,如何
DockPanel
填充 的整个宽度StackPanel
,即它的父级?现在发生的是,即使TextBlock
s 中StackPanel
的宽度超过 的宽度DockPanel
,它也不会拉伸以匹配它们的宽度。
Thanks for the help.
谢谢您的帮助。
回答by Fredrik Hedblad
You can make the Content of every ListBoxItem
stretch by setting HorizontalContentAlignment
in the ItemContainerStyle
您可以ListBoxItem
通过HorizontalContentAlignment
在 ItemContainerStyle 中设置来制作每个拉伸的内容
<ListBox ...>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>