Mouse 'hover' for DataGrid Cell

Jan 26, 2009 at 3:32 AM
How in the world do you capture mouse events? 

I have a requirement to catch the mouse enter/exit from a cell and display a rather eloborate user control...  I have the rest of the code written, but cannot seem to see how to hook into the Mouse events for a specific cell.
Jan 26, 2009 at 8:35 AM

Unfortunately MouseLeave / MouseEnter are not routed events so do not traverse up and down the visual tree. This means that you would have to provide an event handler for each cell.

You could manually detect enter/ / leave. If you handle the MouseMove event on the grid itself, the event arguments contains an OriginalSource property. If you inspect the visual tree starting at this element, you will see that you can travel up the tree to find the cell that the mouse is currently over. Take a look at this blog post for a few more details:

Using this technique, you should be able to work ou for yourself when the mouse has entered / left a cell.

Hope that helps,

Colin E.
-- - my WPF blog - WPF DataGrid Practical Examples

Jan 27, 2009 at 6:14 AM
DataGrid has CellStyle property. So create a Style element and add EventSetters in it wherein you can provide a MouseOver event and a local subroutine based event handler.. something like this (may not be accurate)

<Style TargetType={x:Type dg:DataGridCell}>
    <EventSetter Event="MouseOver" Handler="DataGridCell_MouseOver"/>

<dg:DataGrid x:Name="MyDataGrid" ...>...<./dg:DataGrid>

DataGridCell_MouseOver/Leave events will have the e.OriginalSource as DataGrid and sender as DataGridCell on which mouse event occurred.

Jan 27, 2009 at 2:15 PM
That is what I was thinking too, but could not get that to work.

Where would this go in the Markup?