问题描述
我有一个 GridView,我在代码隐藏中设置了 ItemsSource.网格中的所有列均在 XAML 中定义,所有列宽均为自动".当我最初设置网格的 ItemsSource 时,列宽设置正确.
I have a GridView where I'm setting the ItemsSource in code-behind. All columns in the grid are defined in XAML, and all column widths are "Auto". When I initially set ItemsSource of the grid, the column widths are set correctly.
现在,根据用户的操作,网格的 ItemsSource 可能会设置为新的 EntityCollection.我注意到的是,列宽与之前的 ItemsSource 保持一致.也就是说,当为网格设置新的 ItemsSource 时,列宽似乎不会自动调整.代码隐藏或 XAML 中是否有任何方法可以在设置列宽时强制 Grid 使用新的 ItemsSource?我认为这是 GridView 在 ItemsSource 重置时会自动执行的操作.
Now, depending on the user's actions, the ItemsSource of the grid may be set to a new EntityCollection. What I have noticed is that the column widths remain as they were with the previous ItemsSource. That is, the column widths don't seem to adjust themselves automatically when a new ItemsSource is set for the Grid. Is there any way in code-behind or XAML to force the Grid to use the new ItemsSource when setting the column widths? I would think that this would be something that the GridView would do automatically when it's ItemsSource is reset.
<ScrollViewer VerticalScrollBarVisibility="Auto">
<ListView>
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Width="Auto" Header="Status">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Image Width="16" Height="16" Source="{Binding Path=Blocking}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="Auto" Header="Title">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock TextTrimming="CharacterEllipsis" Text="{Binding}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
</ScrollViewer>
推荐答案
更新ItemsSource后使用此代码:
Use this code after updating ItemsSource:
public void AutoSizeGridViewColumns(ListView listView)
{
GridView gridView = listView.View as GridView;
if (gridView != null)
{
foreach (var column in gridView.Columns)
{
if (double.IsNaN(column.Width))
column.Width = column.ActualWidth;
column.Width = double.NaN;
}
}
}
这篇关于更改 ItemsSource 时,GridView 列宽不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!