简体   繁体   中英

How to select a row when clicking in an empty column?

The XAML markup has a DataGrid that is partially filled with columns.
Behind the data columns there is an empty column that fills the remaining width of the DataGrid.
When the user clicks on a row in this space, the row is not selected.
Can this be changed somehow?

在此处输入图像描述

The highlighted empty space is not a real row or column in the sense that it is represented as DataGridCell or DataGridColumn . The grid lines are rendered using the Grid.ShowGridLines feature.

Of course, you could capture the mouse position and map it to a row, using the framework's hit-test API by calling VisualTreeHelper.HitTest .

A simpler solution would be to to allow the last column to occupy the remaining space by setting DataGridColumn.Width to * .

If your columns are defined explicitly, then you can set it locally on the column element:

<DataGrid AutoGenerateColumns="False">
  <DataGrid.Columns>
    <DataGridTextColumn />
    <DataGridTextColumn Header="Length"
                        Width="*" />
  </DataGrid.Columns>
</DataGrid>

Otherwise you should handle the DataGrid.AutoGeneratedColumns event:

XAML

<DataGrid AutoGenerateColumns="True"
          AutoGeneratedColumns="DataGrid_AutoGeneratedColumns" />

Code-behind

private void DataGrid_AutoGeneratedColumns(object sender, EventArgs e)
{
  var dataGrid = sender as DataGrid;
  double totalColumnWidth = dataGrid.Columns.Sum(column => column.ActualWidth);
  if (totalColumnWidth < dataGrid.ActualWidth)
  {
    dataGrid.Columns.Last().Width = new DataGridLength(1, DataGridLengthUnitType.Star);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM