How to automatically expand a ListView column to populate the containing Grid in WPF?

I created a ListView consisting of two columns: File Name and Size (MB). This ListView is contained in the grid. Since the file names are probably larger than the file sizes, I want to isolate as large the width of the file name column as possible without damaging the size column. In other words, I want the “size” column to match its contents and the “file name” column to fill in the rest of the grid.

I play with many parameters, but I can achieve my goal.

My last attempt looks like this:

                <ListView Name="BrowseFilesListView">                        
                    <ListView.ItemContainerStyle>
                        <Style TargetType="ListViewItem">
                            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                        </Style>
                    </ListView.ItemContainerStyle>                        
                    <ListView.View>
                        <GridView>                               
                            <GridViewColumn Header="File Name"> 
                                <GridViewColumn.CellTemplate>
                                    <DataTemplate>
                                        <TextBlock Text="{Binding Name}" HorizontalAlignment="Stretch"/>
                                    </DataTemplate>
                                </GridViewColumn.CellTemplate>
                            </GridViewColumn>
                            <GridViewColumn Width="Auto" Header="Size (MB)" DisplayMemberBinding="{Binding Path=Size}"/>
                        </GridView>
                    </ListView.View>
                </ListView>

Can anybody help me?

+3
source share
2 answers

:

var gridView = SearchResultsTable.View as GridView;
var columns = new GridViewColumnCollection();
if (gridView != null)
{
    columns = gridView.Columns;
}
var width = BrowseFilesListView.ActualWidth;
var sizeWidth = columns[1].ActualWidth; // columns[0] is the Filename, etc.
const int padding = 10; // slightly hackish
columns[0].Width = width - sizeWidth - padding;

view codebehind Window_Loaded. ; , , .

0

Source: https://habr.com/ru/post/1774295/


All Articles