WPF学习笔记(3):ListView根据内容自动调整列宽
时间: 2024-03-01 14:51:32 浏览: 257
ListView 自动调整列宽
5星 · 资源好评率100%
ListView根据内容自动调整列宽可以让界面更加美观和易于使用。以下是实现的步骤:
1. 确定ListView的列数和列名。
2. 将ListView的View属性设置为GridView。
3. 为每个列设置一个HeaderTemplate,其中包含一个TextBlock控件。
4. 在ListView的Loaded事件中添加代码,使用ActualWidth属性设置每个列的宽度。
5. 在ListView的SizeChanged事件中添加代码,使用ActualWidth属性设置每个列的宽度。
下面是一个示例,演示如何在WPF中自动调整ListView列宽:
```xml
<ListView ItemsSource="{Binding Items}" Loaded="ListView_Loaded" SizeChanged="ListView_SizeChanged">
<ListView.View>
<GridView>
<GridViewColumn Header="ID" Width="Auto">
<GridViewColumn.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</GridViewColumn.HeaderTemplate>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding ID}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Name" Width="Auto">
<GridViewColumn.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</GridViewColumn.HeaderTemplate>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Age" Width="Auto">
<GridViewColumn.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</GridViewColumn.HeaderTemplate>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Age}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
```
```csharp
private void ListView_Loaded(object sender, RoutedEventArgs e)
{
var listView = sender as ListView;
if (listView != null && listView.Items.Count > 0)
{
var gridView = listView.View as GridView;
if (gridView != null)
{
double workingWidth = listView.ActualWidth - SystemParameters.VerticalScrollBarWidth;
for (int i = 0; i < gridView.Columns.Count; i++)
{
gridView.Columns[i].Width = workingWidth / gridView.Columns.Count;
}
}
}
}
private void ListView_SizeChanged(object sender, SizeChangedEventArgs e)
{
var listView = sender as ListView;
if (listView != null && listView.Items.Count > 0)
{
var gridView = listView.View as GridView;
if (gridView != null)
{
double workingWidth = listView.ActualWidth - SystemParameters.VerticalScrollBarWidth;
for (int i = 0; i < gridView.Columns.Count; i++)
{
gridView.Columns[i].Width = workingWidth / gridView.Columns.Count;
}
}
}
}
```
在这个示例中,我们创建了一个包含三列的ListView,每个列的宽度都设置为Auto。在ListView的Loaded和SizeChanged事件中,我们使用ActualWidth属性计算每个列的宽度,以便使列宽适合ListView的大小。当ListView的大小改变时,我们重新计算列宽。
阅读全文