我有一个在两个不同视图中使用的DataGrid。在每种情况下,如果用户调整主机控件/视图的大小,我想让最后一列调整其宽度。
你会怎么做?
干杯,
Berryl
... 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>
我刚刚在xaml中命名了列,并将以下代码放入代码隐藏中。如果有人有更好的想法或优化方法,请告诉我!
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);
}
}
答案 0 :(得分:2)
简单,只需替换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中为此提供了支持。
“*”表示AutoSize值:)
答案 1 :(得分:1)
我简化了原始发布'更新'中的代码并修复了其中的错误。 Jason建议使用“*”大小更简单,因此当网格本身不在UserControl中时应该使用,但我不知道在UserControl内部保持列大小正确的更好方法。
干杯,
Berryl
下面的代码假设有一个名为DataGrid(即dgProject)和一个命名列(即colDescription),需要在调整控件大小时调整其大小。
public partial class Listing : UserControl
{
public Listing()
{
InitializeComponent();
SizeChanged += OnSizeChanged;
}
private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
// split if control is not loaded yet
if (!dgProject.IsLoaded) return;
// only interested in width, not height
if (!e.WidthChanged) return;
var delta = e.NewSize.Width - e.PreviousSize.Width;
var newWidth = colDescription.ActualWidth + delta;
if (newWidth <= colDescription.MinWidth || newWidth >= colDescription.MaxWidth) return;
colDescription.Width = new DataGridLength(newWidth);
}