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