Skip to main content

How to limit zooming/panning to specific Axis value

There is no property, which could limit Axis range, but you can use event handler to control it. If you use normal zooming functionality (with mouse wheel or drawing rectangle), then Chart.ViewXY.BeforeZooming event is fired. Event argument tells new and old Axes ranges. Therefore, you can compare value and Cancel zooming (there is flag for that in event handler).

It also possible to use Chart.ViewXY.Zoomed += View_Zoomed event handler to set specific values. For example in ExampleAreaXY from Demo XAxis is prevented from zoom-out in certain range:

/// <summary>
/// Horizontal zooming logic.
/// </summary>
/// <param name="sender">ViewXY.</param>
/// <param name="e">Event arguments.</param>
private void View_Zoomed(object sender, ZoomedXYEventArgs e)
{
double min = 0;
double max = 1000;

ViewXY view = _chart.ViewXY;

double currentMin = view.XAxes[0].Minimum;
double currentMax = view.XAxes[0].Maximum;

if (min > currentMin || max < currentMax)
{
if (min > currentMin)
currentMin = min;
if (max < currentMax)
currentMax = max;

_chart.BeginUpdate();
view.XAxes[0].SetRange(currentMin, currentMax);
_chart.EndUpdate();
}
}

Alternative and more general is to use Axis.RangeChanged event handler. This is raised for any panning/zooming event that may happen on the chart. In event handler you can check values and call Axis.SetRange() with desired limitations. Note that later method will initiate range change and new Axis.RangeChanged (therefore, you may want to unsubscribe temporary).

private void axisX_RangeChanged(object sender, RangeChangedEventArgs e)
{
double _xMinStopValue = 0;
double _xMaxStopValue = 1000;

double dNewMin = e.NewMin;
double dNewMax = e.NewMax;

// apply Stop values so that zooming/panning could not go outside this range
if (dNewMin < _xMinStopValue)
{
dNewMin = _xMinStopValue;
dNewMax = e.NewMax + _xMinStopValue - e.NewMin;
}

if (_xMaxStopValue < dNewMax)
{
dNewMax = _xMaxStopValue;
if (dNewMin != _xMinStopValue)
{
dNewMin = Math.Max(_xMinStopValue, e.NewMin + _xMaxStopValue - e.NewMax);
}
}

_chart.BeginUpdate();
_chart.ViewXY.XAxes[0].RangeChanged -= axisX_RangeChanged;
_chart.ViewXY.XAxes[0].SetRange(dNewMin, dNewMax);
_chart.ViewXY.XAxes[0].RangeChanged += axisX_RangeChanged;
_chart.EndUpdate();
}