【问题标题】:Set list items to grow to the width of the containing ListView - WPF设置列表项以增长到包含 ListView 的宽度 - WPF
【发布时间】:2011-03-21 20:17:32
【问题描述】:

我希望我的ListView 的项目能够增长到占据ListView 内可用空间的整个宽度。

目前,我将项目的宽度设置为这样(ListView 名为 listView):

Width="{Binding ActualWidth, ElementName=listView, Mode=OneWay}"

项目将占据ListView 的宽度。但是,不考虑垂直滚动条。如果存在滚动条,则将其绘制在项目的右边缘之上。

有办法解决吗?

【问题讨论】:

  • 不确定你想要什么 - ListViewItems 不是默认使用全宽吗?
  • 我没有使用 ListViewItem,我使用 ItemTemplate 来定义 ItemsSource 绑定的视图。

标签: wpf listview binding width actualwidth


【解决方案1】:

我通过直接引用 ItemsPresenter 解决了这个问题。为此,我需要为 Viewbox 定义一个模板并命名 ItemsPresenter。

模板如下所示:

<ListView.Template>
    <ControlTemplate TargetType="{x:Type ListView}">
        <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="1" SnapsToDevicePixels="true">
            <ScrollViewer Focusable="false" Padding="{TemplateBinding Padding}">
                <ItemsPresenter x:Name="MLVItemsPresenter" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
            </ScrollViewer>
        </Border>
       <--SNIP-->
    </ControlTemplate>
</ListView.Template>

宽度绑定看起来像这样:

Width="{Binding ActualWidth, ElementName=MLVItemsPresenter, Mode=OneWay}"

【讨论】:

    【解决方案2】:

    只是一个想法,但如果你删除了所有 wWidth 设置呢?

    当我使用时:

        <ListView DockPanel.Dock="Top">
            <ListViewItem Background="Orange">aaa</ListViewItem>
            <ListViewItem>aaa</ListViewItem>            
        </ListView>
    

    橙色项跨越 ListView 的整个宽度...

    【讨论】:

    • 我对 WPF 比较陌生,但根据我的经验,这不会发生。橙色项目将仅跨越其内容所需的宽度。在这种情况下,'aaa' 的宽度。如果内容大于可用空间,则会要求它们缩小。但是如果它们更小,则不会要求它们扩展(我希望它们扩展)。在我的例子中,列表项是在 ItemTemplate 中定义的,所以这可能就是我的行为不同的原因。
    • 我刚刚检查过了。是的,这是 ListViewItem 的行为。但我没有使用它们,我使用的是 ItemTemplate。是否可以将 ItemTemplate 设置为 ListViewItem?
    【解决方案3】:

    ActualWidth 包含滚动条,所以我认为没有办法解决这个问题。使用ViewBox 怎么样?

    【讨论】:

    • 如何使用 Viewbox?如果我将我的物品包装在 Viewbox 中,就会发生各种不好的事情。我想要求项目增长以适应可用空间。 Viewbox 允许内容使用他们想要的任何空间,然后它会强制扩展或缩小它们以适应可用空间。似乎应该有一些方法来引用 ListView 内的 ScrollViewer 中包含的 ItemsPresenter 的宽度。这应该是我正在寻找的宽度...
    猜你喜欢
    • 1970-01-01
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多