This blog post will demonstrate how to add location crosshair for RadChart as well as location indicator (achieved by two TextBlock-s that track the current mouse location).
To achieve the crosshair functionality you will add two custom gridlines to the ChartArea (each of them parallel to one of the axes). Also, you will need three events – MouseEnter, MouseLeave and MouseMove to track the mouse cursor position and “move” the gridlines across the plot area. By handling the MouseEnter and MouseLeave events you’ll change the visibility of the gridlines to Visible and Collapsed whenever the mouse cursor enters or leaves the bounds of the plot area .
The Mouse Move event handler in the code behind finds the current mouse position within the plot area. Note that you need to calculate the respective mouse coordinates relative to the plot area (represented by ClipPanel element in the ChartArea template) and not to the ChartArea itself. You can easily get hold of the panel via the ChildrenOfType<T> extension method (add reference to the Telerik.Windows.Controls namespace) like this:
Now that you have the correct mouse coordinates, you need to pass the information to the custom gridline elements as well. However, the gridlines expect and work with data units and not physical pixels so a transformation must be applied first. Each axis exposes ConvertPhysicalUnitsToData() method that can handle the actual conversion from physical pixels to data units. Note that if you need the same functionality on mouse click, you do not need to perform the conversion manually, as RadChart provides already converted values through the event arguments for the ChartArea.PlotAreaMouseLeftButtonDown / ChartArea.PlotAreaMouseLeftButtonUp events.
Knowing the current X and Y data values of the mouse cursor you can bind the pair of lines to the X and Y properties of their DataContext, ensuring that the two lines will intersect at the current mouse location.
The Location Indicator will inherit the PlotArea’s DataContext, allowing it to output the current location in the chart coordinate system.
You can download the full source code from here
Subscribe to be the first to get our expert-written articles and tutorials for developers!