Question

I want to catch MouseDown events for all cells of the DataGrid object. I've specified a handler for it:

<DataGrid AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left" Margin="66,119,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="200" ItemsSource="{Binding}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}" />
                <DataGridTextColumn Header="Text" Binding="{Binding Path=Text}" />
            </DataGrid.Columns>
            <DataGrid.Resources>
                <Style TargetType="{x:Type DataGridCell}">
                    <EventSetter Event="MouseDown" Handler="CellMouseDown" />
                </Style>
            </DataGrid.Resources>
        </DataGrid>

But the event handler doesn't get called. Why?

Was it helpful?

Solution

One reason may be that the event is handled inside the DataGridCell, so it does not reach your handler. You can try the tunneling version of the event which is PreviewMouseDown.

OTHER TIPS

Your event is probably being handled by another handler while its going to your handler.

Here is an overview of Routed events

The 3 types of events are :

Bubbling: Event handlers on the event source are invoked. The routed event then routes to successive parent elements until reaching the element tree root. Most routed events use the bubbling routing strategy. Bubbling routed events are generally used to report input or state changes from distinct controls or other UI elements.

Direct: Only the source element itself is given the opportunity to invoke handlers in response. This is analogous to the "routing" that Windows Forms uses for events. However, unlike a standard CLR event, direct routed events support class handling (class handling is explained in an upcoming section) and can be used by EventSetter and EventTrigger.

Tunneling: Initially, event handlers at the element tree root are invoked. The routed event then travels a route through successive child elements along the route, towards the node element that is the routed event source (the element that raised the routed event). Tunneling routed events are often used or handled as part of the compositing for a control, such that events from composite parts can be deliberately suppressed or replaced by events that are specific to the complete control. Input events provided in WPF often come implemented as a tunneling/bubbling pair. Tunneling events are also sometimes referred to as Preview events, because of a naming convention that is used for the pairs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top