在Microsoft Chart控件中启用鼠标滚轮缩放

7

如何在使用鼠标滚轮时启用 Microsoft Chart 控件的缩放功能

我有以下代码,想知道如何制作此事件?它属于哪个类别?

private void chData_MouseWheel(object sender, MouseEventArgs e)
{
    try
    {
        if (e.Delta < 0)
        {
            chart1.ChartAreas[0].AxisX.ScaleView.ZoomReset();
            chart1.ChartAreas[0].AxisY.ScaleView.ZoomReset();
        }

        if (e.Delta > 0)
        {
            double xMin = chart1.ChartAreas[0].AxisX.ScaleView.ViewMinimum;
            double xMax = chart1.ChartAreas[0].AxisX.ScaleView.ViewMaximum;
            double yMin = chart1.ChartAreas[0].AxisY.ScaleView.ViewMinimum;
            double yMax = chart1.ChartAreas[0].AxisY.ScaleView.ViewMaximum;

            double posXStart = chart1.ChartAreas[0].AxisX.PixelPositionToValue(e.Location.X) - (xMax - xMin) / 4;
            double posXFinish = chart1.ChartAreas[0].AxisX.PixelPositionToValue(e.Location.X) + (xMax - xMin) / 4;
            double posYStart = chart1.ChartAreas[0].AxisY.PixelPositionToValue(e.Location.Y) - (yMax - yMin) / 4;
            double posYFinish = chart1.ChartAreas[0].AxisY.PixelPositionToValue(e.Location.Y) + (yMax - yMin) / 4;

            chart1.ChartAreas[0].AxisX.ScaleView.Zoom(posXStart, posXFinish);
            chart1.ChartAreas[0].AxisY.ScaleView.Zoom(posYStart, posYFinish);
        }
    }
    catch { }            
}
2个回答

5
我认为上面的答案应该是:
chData.MouseWheel += new MouseEventHandler(chData_MouseWheel);
但是根据我所发现的,只要您没有在代码中设置对图表控件的焦点,图表的鼠标滚轮就不起作用。因此,我使用了图表控件的mouse-enter事件来设置焦点到图表,并使用chart control的mouse-leave事件将控件设置回其父级。
因此,您需要添加以下代码行到您的代码中,相应地绑定图表控件的mouse-leave和mouse-enter事件,并加入以上代码行。
    private void chartTracking_MouseEnter(object sender, EventArgs e)
    {
        this.chartTracking.Focus();
    }

    private void chartTracking_MouseLeave(object sender, EventArgs e)
    {
        this.chartTracking.Parent.Focus();
    }

3
您所拥有的是一个处理MouseWheel事件的处理程序方法。您需要将处理程序方法附加到图表控件的MouseWheel事件上。从方法签名中可以看出,我假设您的图表控件名称为chData,因此您可以在表单的构造函数中使用以下代码:
chData.MouseWheel += new EventHandler(chData_MouseWheel);

当然,您也可以在设计时将处理程序与事件关联起来。要这样做,请使用“属性窗口”,单击工具栏中的闪电图标以切换到“事件”视图。然后找到MouseWheel事件,单击下拉箭头并选择处理程序方法的签名。这将导致设计器将上述代码编写到您的窗体的代码后面文件中。
除此之外,您的代码中还有一个巨大的红旗:一个空的catch块。如果您没有处理异常或对其进行任何操作,则不应捕获它。这不是口袋妖怪,不能因为抓住了所有异常而获得奖励。

四年后,仍然可以开怀大笑。 - vipersassassin

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