Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataGrid full row selection

I'm using WPF and .NET 4.0. Recently in one of my programs I switched from using ListView with GridView to DataGrid.

I want to be able to select and highlight the whole row like I was able to do in ListView.

In ListView, when I click on the empty space right from the last column, I'm still able to select the row. The whole row is highlighted, not only the cells.

In DataGrid however, after setting SelectionMode="Single" and SelectionUnit="FullRow", the row is selectable only when I click on any cell in it, not in the empty space right to the last column.

How can I use the highlighting behavior from ListView here?

like image 798
madbadger Avatar asked Apr 01 '11 21:04

madbadger


People also ask

How to select row in DataGrid in WPF?

WPF DataGrid (SfDataGrid) allows you to select one or more rows or cells. For selecting specific row or group of rows you have to set SelectionUnit as Row and for selecting a specific cell or group of cells you have to set SelectionUnit as Cell or Any. In SelectionUnit.

How to remove Selected row from DataGrid in WPF?

You can access the currently selected item of a DataGrid using the SelectedItem property. After the first line you need to extract the information (e.g. some Id) from the item in order to delete it in the database. Usually you cast the SelectedItem to the object you used to bind to the grid. See also this response.


2 Answers

There are two solutions:

  1. Set the width of the last column in the DataGrid to Width="*".
  2. The second solution is a workaround. Add an additional empty column after the last column (i.e. neither setting its Header nor Binding properties) and set its width to Width="*"

I personally prefer the first solution; it's cleaner than the second one.

like image 139
Mohammed A. Fadil Avatar answered Oct 14 '22 06:10

Mohammed A. Fadil


There is one more solution if you can use code behind in your project. You can handle mouse down event of datagrid and programmatically select the clicked row:

 private void SomeGridMouseDown(object sender, MouseButtonEventArgs e)
    {
        var dependencyObject = (DependencyObject)e.OriginalSource;

        //get clicked row from Visual Tree
        while ((dependencyObject != null) && !(dependencyObject is DataGridRow))
        {
            dependencyObject = VisualTreeHelper.GetParent(dependencyObject);
        }

        var row = dependencyObject as DataGridRow;
        if (row == null)
        {
            return;
        }

        row.IsSelected = true;
    }
like image 27
Aleksey L. Avatar answered Oct 14 '22 05:10

Aleksey L.