0

我有一个 wpf 项目,我正在研究如何在列表视图中调整网格视图的大小。

网格设置

         <Grid.ColumnDefinitions>
        <ColumnDefinition Width="auto" MinWidth="144"/>
        <ColumnDefinition Width="*" MinWidth="136"/>               
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" MinHeight="93"/>

    </Grid.RowDefinitions>

这是我的列表视图

       <ListView Grid.Column="0" Grid.Row="0" x:Name="view" ItemsSource="{Binding}" SizeChanged="ListView_SizeChanged" Loaded="ListView_Loaded">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Test" 
                                         DisplayMemberBinding="{Binding Path=Name}"/>
                <GridViewColumn Header="Test2" 
                                         DisplayMemberBinding="{Binding Path=Name}"/>
                <GridViewColumn Header="Test3" 
                                         DisplayMemberBinding="{Binding Path=Name}"/>
            </GridView>
        </ListView.View>

添加代码以删除列表视图生成的不需要的列

    private void ListView_SizeChanged(object sender, SizeChangedEventArgs e)
   {
       UpdateColumnsWidth(sender as ListView);
   }

   private void ListView_Loaded(object sender, RoutedEventArgs e)
   {
       UpdateColumnsWidth(sender as ListView);
   }

   // To remove the last empty column created by Listview
   private void UpdateColumnsWidth(ListView listView)
   {
       var gridView = listView.View as GridView;
       if (gridView != null)
       {
           int autoFillColumnIndex = gridView.Columns.Count - 1;
           if (double.IsNaN(listView.ActualWidth))
               listView.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
           double remainingSpace = gridView.Columns.Where((t, i) => i != autoFillColumnIndex).Aggregate(listView.ActualWidth, (current, t) => current - t.ActualWidth);
           gridView.Columns[autoFillColumnIndex].Width = remainingSpace >= 0 ? remainingSpace : 0;
       }

在此处输入图像描述

现在我遇到的问题是最后一列占用了我没有分配的更大空间。当我调整窗口大小时,我希望我的所有列都有一个比例空间。但是现在当我展开最后一列时会占用很多空间。

4

1 回答 1

0

您的代码明确设置一列以占用所有剩余空间。相反,您需要将它们全部设置为相同的值,即ListView宽度除以列数:

if (double.IsNaN(listView.ActualWidth))
    listView.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));

double colWidth = listView.ActualWidth / gridView.Columns.Count;
for (int i = 0; i < gridView.Columns.Count; ++i)
    gridView.Columns[i].Width = colWidth;
于 2013-06-28T15:34:36.613 回答