我有一个wpf项目我正在研究如何在listview中调整gridview的大小。
网格设置
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" MinWidth="144"/>
<ColumnDefinition Width="*" MinWidth="136"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" MinHeight="93"/>
</Grid.RowDefinitions>
这是我的ListView
<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>
添加了代码以删除listview生成的不需要的列
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;
}
现在我遇到的问题是最后一列占用了更大的空间,我没有为它分配。当我调整窗口大小时,我希望我的所有列都有一个比例空间。但是现在,当我扩展最后一列时需要很大的空间。
答案 0 :(得分: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;