当单击行时,Silverlight DataGrid的MouseLeftButtonDown事件不会触发

3

注意:我已经找到了解决方法,所以我发布这篇文章只是为了参考,但如果有更好的解决方案,我也很乐意接受教育。

我正在尝试通过钩入UIElement.MouseLeftButtonDown来提供Silverlight DataGrid的双击功能,但当我使用XAML或DataGrid.MouseLeftButtonDown +=语法订阅DataGrid.MouseLeftButtonDown时,当我单击DataGrid中的行时,我的事件处理程序没有被调用。如果我点击标题,事件会被触发。

如果我在父级UserControl级别上订阅相同的事件,则根据Silverlight RoutedEvents,事件处理程序将成功调用,但然后我必须检测点击是否发生在DataGrid上还是其他地方。

如果我使用下面显示的UIElement.AddHandler语法订阅事件,那么它将按照handledEventsToo: true参数的预期工作。

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

看起来,DataGrid 的实现在其中一个子 UIElement 上默认将这些事件标记为已处理,阻止了事件冒泡,这并不是我最初期望的。经过更深入的思考,我可以看到点击行为驱动各种操作(选择项目、编辑字段等),因此也许这种实现是有意义的。

1个回答

2

我曾经遇到过同样的问题,我使用了MouseLeftButtonUp来触发事件,但是clickcount值总是1。

以下是解决方法:

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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接