我有一个用于两个不同视图的DataGrid.在每种情况下,如果用户调整主机控件/视图的大小,我都希望最后一列的大小为其宽度.
你会怎么做?
干杯,
贝里
…
CanUserResizeColumns =“真实”
>
<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(工作代码)
我只是在xaml中命名该列,然后将以下代码放入代码隐藏中.如果有人有更好的主意或优化方法,请告诉我!
public partial class Listing : UserControl
{
private double _currentColumnWidth;
public Listing()
{
InitializeComponent();
Loaded += onl oaded;
SizeChanged += OnSizeChanged;
}
private void onl oaded(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);
}
}
解决方法:
简单,只需替换XAML中的width属性
<DataGridTextColumn
Header="Description" Binding="{Binding Description}"
IsReadOnly="True"
CanUserSort="True" SortDirection="Ascending" CanUserResize="True"
MinWidth="260" Width="Auto" />
至 …
<DataGridTextColumn
Header="Description" Binding="{Binding Description}" IsReadOnly="True"
CanUserSort="True" SortDirection="Ascending" CanUserResize="True"
MinWidth="260" Width="*" />
您不需要任何代码来进行宽度的处理,因为WPF可以在XAML中满足此要求.
“ *”表示自动尺寸值:)