简体   繁体   English

如何使StackPanel或DockPanel拉伸以适应WPF中的容器?

[英]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: 我有两个问题:

  1. How do I make the 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. 现在,它只需要足够的空间来容纳DockPanelTextBlock It won't fit the width of the ListBox or ListBoxItem . 它不适合ListBoxListBoxItem的宽度。
  2. Next, how do I make the 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM