如何使 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:36:43  来源:igfitidea点击:

How to make the StackPanel or DockPanel stretch to fit their containers in WPF?

wpf

提问by Boris

I have a Gridas 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 ListBoxinside 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 ListBoxto be a vertically oriented StackPanel, with one DockPaneland a couple of TextBlocks inside.

我有一个Grid定义了两列的根容器(只有一行)。
第一列具有灵活的宽度,第二列具有 300px 的固定宽度。
接下来,我ListBox在第二列内放置了一个以水平和垂直拉伸,即填充整个第二列。
最后,我定义了ListBox一个垂直方向的 Items 模板StackPanel,里面有一个DockPanel和几个TextBlocks。

<!-- 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:

我有两个问题:

  1. How do I make the StackPanelfill the entire width of the ListBox? Right now, it only takes enough space to accomodate the DockPaneland the TextBlocks inside. It won't fit the width of the ListBoxor ListBoxItem.
  2. Next, how do I make the DockPanelfill the entire width of the StackPanel, i.e. its parent? What happens right now is that even if the width of the TextBlocks in the StackPanelexceed the width of the DockPanel, it won't stretch to match their width.
  1. 如何StackPanel填充整个宽度ListBox?现在,它只需要足够的空间来容纳里面的DockPanelTextBlocks。它不适合ListBoxor的宽度ListBoxItem
  2. 接下来,如何DockPanel填充 的整个宽度StackPanel,即它的父级?现在发生的是,即使TextBlocks 中StackPanel的宽度超过 的宽度DockPanel,它也不会拉伸以匹配它们的宽度。

Thanks for the help.

谢谢您的帮助。

回答by Fredrik Hedblad

You can make the Content of every ListBoxItemstretch by setting HorizontalContentAlignmentin the ItemContainerStyle

您可以ListBoxItem通过HorizontalContentAlignment在 ItemContainerStyle 中设置来制作每个拉伸的内容

<ListBox ...>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>