如何使用鼠标滚轮启用Microsoft图表控件放大

yog*_*dra 21 c# microsoft-chart-controls

我在我的项目中使用Microsoft Chart控件,我想通过使用鼠标滚轮启用Chart Control中的缩放功能,我该如何实现?

但是用户不必点击图表,应该就像鼠标位置在我的图表上而不是从鼠标滚轮那个点开始它可以放大/缩小

tmw*_*ods 26

你会想要使用这个MouseWheel活动.

首先使图表的两个轴都可缩放:

chart1.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
chart1.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
Run Code Online (Sandbox Code Playgroud)

并分配事件:

chart1.MouseWheel += chart1_MouseWheel;
Run Code Online (Sandbox Code Playgroud)

然后在事件处理程序中:

private void chart1_MouseWheel(object sender, MouseEventArgs e)
{
    var chart = (Chart)sender;
    var xAxis = chart.ChartAreas[0].AxisX;
    var yAxis = chart.ChartAreas[0].AxisY;

    try
    {
        if (e.Delta < 0) // Scrolled down.
        {
            xAxis.ScaleView.ZoomReset();
            yAxis.ScaleView.ZoomReset();
        }
        else if (e.Delta > 0) // Scrolled up.
        {
            var xMin = xAxis.ScaleView.ViewMinimum;
            var xMax = xAxis.ScaleView.ViewMaximum;
            var yMin = yAxis.ScaleView.ViewMinimum;
            var yMax = yAxis.ScaleView.ViewMaximum;

            var posXStart = xAxis.PixelPositionToValue(e.Location.X) - (xMax - xMin) / 4;
            var posXFinish = xAxis.PixelPositionToValue(e.Location.X) + (xMax - xMin) / 4;
            var posYStart = yAxis.PixelPositionToValue(e.Location.Y) - (yMax - yMin) / 4;
            var posYFinish = yAxis.PixelPositionToValue(e.Location.Y) + (yMax - yMin) / 4;

            xAxis.ScaleView.Zoom(posXStart, posXFinish);
            yAxis.ScaleView.Zoom(posYStart, posYFinish);
        }
    }
    catch { }            
}
Run Code Online (Sandbox Code Playgroud)

e.Delta属性告诉您已经完成了多少轮"滚动",并且可能很有用.
向外滚动将缩小整个过程.

这可能是一种更清洁的方式,但事实确实如此.希望这可以帮助!

  • 显然,你必须首先执行此操作`void friendChart_MouseLeave(object sender,EventArgs e){if(friendChart.Focused)friendChart.Parent.Focus(); } void friendChart_MouseEnter(object sender,EventArgs e){if(!friendChart.Focused)friendChart.Focus(); }`[鼠标轮事件未触发](http://stackoverflow.com/questions/13782763/mousewheel-event-not-firing) (2认同)