How to get row particular element belong to in WPF DataGrid


Hi, recently I was working very closely with WPF DataGrid and I needed to figure out what row was clicked (if any) by user. As it turned out, this was very easy to implement.

For instance imagine that you handle MouseDown event and when it happens, you need to get row that was clicked:

public partial class MainWindow { public MainWindow() { InitializeComponent(); MouseDown += OnMouseDown; } private void OnMouseDown(object sender, MouseButtonEventArgs mouseButtonEventArgs) { DataGridRow rowContainingElement = DataGridRow.GetRowContainingElement(mouseButtonEventArgs.OriginalSource as FrameworkElement); } }

As you can see, I just use method GetRowContainingElement which takes instance of FrameworkElement (which I took from OriginalSource property of event arguments) and returns instance of DataGridRow that specified FrameworkElement belongs to. In case specified element doesn’t belong to any row, null reference will be returned.

I like these simple solutions provided by WPF Smile.

Advertisements