I have a DataGrid that is used in two different views. In each case, I would like to have the last column resize it’s width if the user resizes the host control/view.
How would you do that?
Cheers,
Berryl
…
CanUserResizeColumns=”True”
>
<DataGrid.Columns>
<DataGridTextColumn
Header="Number" Binding="{Binding BusinessId}" IsReadOnly="True"
CanUserSort="True" CanUserResize="False"
Width="75"/>
<DataGridTextColumn
Header="Description" Binding="{Binding Description}" IsReadOnly="True"
CanUserSort="True" SortDirection="Ascending" CanUserResize="True"
MinWidth="260" Width="Auto" />
</DataGrid.Columns>
</DataGrid>
UPDATE (Working Code)
I just named the column in the xaml and put the following code into the code-behind. If anyone has got a better idea or a way to optimize this, please let me know!
public partial class Listing : UserControl
{
private double _currentColumnWidth;
public Listing()
{
InitializeComponent();
Loaded += OnLoaded;
SizeChanged += OnSizeChanged;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
_currentColumnWidth = colDescription.ActualWidth;
}
private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
// split if control is not loaded yet
if (_currentColumnWidth == 0) return;
// only interested in width, not height
var widthChanged = e.WidthChanged;
if (!widthChanged) return;
var delta = e.NewSize.Width - e.PreviousSize.Width;
var newWidth = _currentColumnWidth + delta;
if (newWidth <= colDescription.MinWidth || newWidth >= colDescription.MaxWidth) return;
_currentColumnWidth = newWidth;
colDescription.Width = new DataGridLength(_currentColumnWidth);
}
}
Easy, just replace the width property in your XAML
to …
You do not require any code behind to do any handling of the width as WPF caters for this in XAML.
the “*” indicates an AutoSize value 🙂