如何使 StackPanel 或 DockPanel 拉伸以适应 WPF 中的容器? [英] How to make the StackPanel or DockPanel stretch to fit their containers in WPF?

查看:54
本文介绍了如何使 StackPanel 或 DockPanel 拉伸以适应 WPF 中的容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Grid 作为根容器,定义了两列(只有一行).
第一列具有灵活的宽度,第二列具有 300 像素的固定宽度.
接下来,我在第二列内放置了一个 ListBox 以水平和垂直拉伸,即填充整个第二列.
最后,我为 ListBox 定义了一个项目模板,它是一个垂直方向的 StackPanel,带有一个 DockPanel 和几个 TextBlock 里面.

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 TextBlocks inside.

<!-- 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" />

我有两个问题:

  1. 如何让 StackPanel 填满 ListBox 的整个宽度?现在,它只需要足够的空间来容纳 DockPanelTextBlock 里面.它不适合 ListBoxListBoxItem 的宽度.
  2. 接下来,如何让 DockPanel 填充 StackPanel 的整个宽度,即它的父级?现在发生的是,即使 StackPanelTextBlock 的宽度超过 DockPanel 的宽度,它也不会拉伸以匹配它们的宽度.
  1. How do I make the StackPanel fill the entire width of the ListBox? Right now, it only takes enough space to accomodate the DockPanel and the TextBlocks inside. It won't fit the width of the ListBox or ListBoxItem.
  2. Next, how do I make the DockPanel fill 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 StackPanel exceed the width of the DockPanel, it won't stretch to match their width.

感谢您的帮助.

推荐答案

您可以通过在 ItemContainerStyle 中设置 Horizo​​ntalContentAlignment 来使每个 ListBoxItem 的 Content 拉伸

You can make the Content of every ListBoxItem stretch by setting HorizontalContentAlignment in the ItemContainerStyle

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

这篇关于如何使 StackPanel 或 DockPanel 拉伸以适应 WPF 中的容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆