Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datagrid row selection event, WPF

I did a simple data binding to a datagrid. Now I would like to get the relevant rowdata (entire row data) when the row is clicked in the datagrid. Do I need to use the mouseclickevent since there are no row selection events?.

like image 494
RobinAtTech Avatar asked Mar 18 '14 22:03

RobinAtTech


2 Answers

private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ProductItem productItem = (ProductItem)dataGrid.SelectedItem; //Datagrid bound with ProductItem 
}
like image 165
RobinAtTech Avatar answered Nov 24 '22 09:11

RobinAtTech


I have done it this way. Others may have a simpler way ! Mine deals with an Observable Collection of a PlayListEntries class for a mediaplayer. Hope this can help

    private void PlayList_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        DependencyObject dep = (DependencyObject)e.OriginalSource;

        // iteratively traverse the visual tree
        while ((dep != null) && !(dep is DataGridCell) && !(dep is DataGridColumnHeader))
        {
            dep = VisualTreeHelper.GetParent(dep);
        }

        if (dep == null)
            return;

        if (dep is DataGridColumnHeader)
        {
            DataGridColumnHeader columnHeader = dep as DataGridColumnHeader;
            // do something
        }

        if (dep is DataGridCell)
        {
            DataGridCell cell = dep as DataGridCell;

            // navigate further up the tree
            while ((dep != null) && !(dep is DataGridRow))
            {
                dep = VisualTreeHelper.GetParent(dep);
            }

            DataGridRow row = dep as DataGridRow;

            var ple = (PlayListEntry)row.Item;

// From here you have access to all of the row.  
// Each column is suitable bound. 
// I can post the xaml if you are not sure.

            //object value = ExtractBoundValue(row, cell);  //4

            //int columnIndex = cell.Column.DisplayIndex;
            //int rowIndex = FindRowIndex(row);

            //var s = string.Format("Cell clicked [{0}, {1}] = {2}",rowIndex, columnIndex, value.ToString());
        }
    } 
like image 41
Jim Avatar answered Nov 24 '22 07:11

Jim