Automatically resize columns of wpf GridView

守給你的承諾、 提交于 2019-12-11 14:12:03

问题


I've gone through a few posts with similar requirements but haven't found a fully working solution yet.

I have a GridView in a ListView with a few columns

        <ListView x:Name="TheList" DockPanel.Dock="Top" 
                  ItemsSource="{Binding Itemlist}"                  
                  SelectionMode="Extended">
            <ListView.View>
                <GridView>
                    ....
                    <GridViewColumn x:Name="valueColumn" Header="Value" DisplayMemberBinding="{Binding ItemValue}" Width="150"/>
                </GridView>
            </ListView.View>
        </ListView>

I set the model and sub to the model's property changing

        _viewModel = new MyModel();
        DataContext = _viewModel;
        _viewModel.ItemValueChanged += RunResizeLogic; //ItemValueChanged gets emitted when the property changes

And then based on some solutions I found I attempt resizing the column

    private void RunResizeLogic(object sender, EventArgs e)
    {
        ResizeGridViewColumn(valueColumn);
    }
    private void ResizeGridViewColumn(GridViewColumn col)
    {
        Dispatcher.Invoke(DispatcherPriority.Normal,
            new Action(() =>
            {
                if (double.IsNaN(col.Width))
                {
                    col.Width = col.ActualWidth;
                }

                col.Width = double.NaN;

            }));
    }

My resize logic gets called when the my ItemValue changes, however, the column is only resizing when ItemValue changes again.

So, if it's current size is 5. the ItemValue size changes to 10, my logic runs with ActualWidth==5, column remains the same size (5). The ItemValue size changes again to 2, logic runs ActualWidth==2 and the column resizes to 10.

What am I doing wrong? Thanks.

EDIT:

Some of the posts I've looked through

  • GridViewColumn Width Adjustment
  • WPF: GridViewColumn resize event

来源:https://stackoverflow.com/questions/35560621/automatically-resize-columns-of-wpf-gridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!