1

In WPF, I have the following:

<ListView.View>
    <GridView>
        <GridViewColumn
            Width="Auto"
            DisplayMemberBinding="{Binding SomeProperty, Mode=OneWay}"
            Header="Type"/>

The problem is that this only auto-sizes the column to the visible content. This is the same behavior when double clicking the header divider as well.

I want it to resize the column according to all content. For contrast, take the Winforms DataGridView equivalent to the current Auto resizing behavior and the equivalent to the desired behavior:

this.dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; // Current behavior
this.dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;       // Desired behavior

Is this possible for a WPF ListView?

This question is different than How to autosize and right-align GridViewColumn data in WPF? and others like it because they still trigger the current resizing behavior for visible content and do not address all content.

4

1 回答 1

2

问题是默认情况下启用了虚拟化ListViewItemsPanel在这种模式下,只会呈现可见内容,然后会触发自动调整列。因此,如果您的 中没有很多项目ListView,您可以通过附加属性关闭虚拟化模式VirtualizingStackPanel.IsVirtualizing,然后它将按预期工作:

<ListView VirtualizingStackPanel.IsVirtualizing="false">
       <!-- ... -->
</ListView>

如果您不想关闭虚拟化,那么我认为没有一些简单的方法可以利用Width="Auto". 您可能必须自己手动实现该功能。从技术上讲,我们需要了解最大宽度以相应地更新列的宽度。每次需要更新列的宽度时,我们都可以创建一些 for 循环,但这很昂贵。我们还可以在每次单元格内容更改时存储最大宽度(这是更好的方法)。无论如何,手动操作很痛苦。

于 2015-09-30T02:02:03.103 回答