更改ItemsSource时,GridView列宽不会更新

时间:2012-01-31 11:38:42

标签: wpf xaml gridview binding itemssource

我有一个GridView,我在代码隐藏中设置ItemsSource。网格中的所有列都在XAML中定义,所有列宽都是“自动”。当我最初设置网格的ItemsSource时,列宽正确设置。

现在,根据用户的操作,可以将网格的ItemsSource设置为新的EntityCollection。我注意到的是,列宽仍然与之前的ItemsSource一样。也就是说,当为Grid设置新的ItemsSource时,列宽似乎不会自动调整。代码隐藏或XAML中是否有任何方法可以在设置列宽时强制Grid使用新的ItemsSource?我认为这将是GridView在重置ItemsSource时自动执行的操作。

<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>

2 个答案:

答案 0 :(得分:8)

更新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; 
        } 
    } 
} 

答案 1 :(得分:2)

我创建了以下类,并在需要的地方使用了GridView

/// <summary>
/// Represents a view mode that displays data items in columns for a System.Windows.Controls.ListView control with auto sized columns based on the column content     
/// </summary>
public class AutoSizedGridView : GridView
{        
    protected override void PrepareItem(ListViewItem item)
    {
        foreach (GridViewColumn  column in Columns)
        {
            //setting NaN for the column width automatically determines the required width enough to hold the content completely.
            //if column width was set to NaN already, set it ActualWidth temporarily and set to NaN. This raises the property change event and re computes the width.
            if (double.IsNaN(column.Width)) column.Width = column.ActualWidth;
            column.Width = double.NaN;              
        }            
        base.PrepareItem(item);
    }
}