我们想在此控件中使用鼠标滚轮时重写DataGridView的默认行为。默认情况下,DataGridView滚动一些等于SystemInformation.MouseWheelScrollLines设置的行。我们想要做的是一次只滚动一个项目。我们在DataGridView中显示的图像有些大,因为这种滚动三行(一个典型的系统设置)太多了,通常会导致用户滚动到他们甚至看不到的项目。)如何让DataGridView使用鼠标滚轮一次滚动一个项目?
我已经尝试了几件事情,迄今为止还没有取得太大的成功。这里有一些问题,我碰到的:
您可以订阅鼠标滚轮事件,但没有办法,以纪念事件的处理,做我自己的事情。
您可以重写OnMouseWheel,但这似乎永远不会被调用。
您可能可以在基本滚动代码中更正此问题,但由于其他类型的滚动(例如,使用键盘)通过相同的管道传递,因此听起来像是一团乱七八糟的工作。
任何人都有很好的建议吗?
下面是最后的代码,使用给出精彩的答案:
/// <summary>
/// Handle the mouse wheel manually due to the fact that we display
/// images, which don't work well when you scroll by more than one
/// item at a time.
/// </summary>
///
/// <param name="sender">
/// sender
/// </param>
/// <param name="e">
/// the mouse event
/// </param>
private void mImageDataGrid_MouseWheel(object sender, MouseEventArgs e)
{
// Hack alert! Through reflection, we know that the passed
// in event argument is actually a handled mouse event argument,
// allowing us to handle this event ourselves.
// See http://tinyurl.com/54o7lc for more info.
HandledMouseEventArgs handledE = (HandledMouseEventArgs) e;
handledE.Handled = true;
// Do the scrolling manually. Move just one row at a time.
int rowIndex = mImageDataGrid.FirstDisplayedScrollingRowIndex;
mImageDataGrid.FirstDisplayedScrollingRowIndex =
e.Delta < 0 ?
Math.Min(rowIndex + 1, mImageDataGrid.RowCount - 1):
Math.Max(rowIndex - 1, 0);
}
谢谢。我认为这会起作用,尽管我选择的答案更简单。 – 2008-09-25 20:44:25