Saturday, September 15, 2012

Silverlight DataGrid MouseLeftButtonDown event not raised when clicking on rows

Silverlight DataGrid MouseLeftButtonDown event not raised when clicking on rows

Note: I have found a solution to my problem so I am posting this for reference purposes, although I would be happy to be educated with a better solution.

I'm trying to provide double click functionality on a Silverlight DataGrid by hooking into the UIElement.MouseLeftButtonDown but when I subscribe to the DataGrid.MouseLeftButtonDown using XAML or the DataGrid.MouseLeftButtonDown += syntax, my event handler is not called when I click on the rows within the DataGrid. If I click on the Header, the event is raised.

If I subscribe to the same event at the parent UserControl level, the event handler is called successfully as you would expect based on Silverlight RoutedEvents but then I have to detect whether the click occurred on the DataGrid or somewhere else.

If I subscribe to the event using this UIElement.AddHandler syntax, as shown below, then it works as expected based on the handledEventsToo: true parameter.

dataGrid.AddHandler(UIElement.MouseLeftButtonDownEvent,                      new MouseButtonEventHandler(dataGrid_MouseLeftButtonDown)                     , handledEventsToo: true); 

It seems that the DataGrid implementation is marking these events as handled, prevent event bubbling, by default in one of the child UIElements, which is not what I expected initially. With more thought I can see that the click behaviour drives all sorts of things (select item, edit field etc.) so perhaps the implementation makes sense.

Answers & Comments...

Answer: 1

I had the same problem and I used MouseLeftButtonUp which fires the event but the clickcount value is always 1.

Here is the fix for that:

private const int MOUSE_SENSITIVITY = 300;

private DateTime _previousClick;  private void exceptionsDataGrid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) {         DataGrid dg = (sender as DataGrid);         DateTime current=DateTime.Now;         LoggerService.Exception exception = (LoggerService.Exception)dg.SelectedItem;         if (_previousClick != null)         {             TimeSpan clickSpan = current - _previousClick;             if (clickSpan.TotalMilliseconds < MOUSE_SENSITIVITY)             {                 MessageBox.Show("You double clicked!");             }         }         _previousClick = current;     } 

by : user1058637http://stackoverflow.com/users/1058637




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog