HowTo : Implement Keyboard Shortcuts for C1Chart
C1Chart for WPF offers powerful rendering, rich styling elements, animations, and data-binding capabilities. This control also has built-in functions that simplify the implementation of interactive behaviors for the end user. The end user can explore, rotate and zoom chart using Mouse and Shift key combinations. However, in certain scenarios you may want to provide direct keyboard operations excluding the mouse interactions. This blog guides you to implement the same. The approach is quite simple. Manually set the focus in the C1Chart and once the focus is set, you can handle the keyboard events and add the required code to reflect the desired behavior on the Chart. Hence, even if the focus shifts to other controls as the user interacts with the UI, the user will just have to click back into the chart and, it will again make the chart responsive to keyboard shortcuts. In this blog, we have shown the ZoomIn/ZoomOut action on the Chart using the KeyDown/KeyUp keys respectively. Following code is used to implement the same :
Private Sub Chart1_MouseLeftButtonDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs Handles Chart1.MouseLeftButtonDown
'Setting the Focus manually.
'Without forcing this Focus, the keyboard events are not recognised.
Chart1.Focus()
End Sub
Private Sub Chart1_PreviewKeyDown(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles Chart1.<span>PreviewKeyDown
Chart1.View.AxisX.MinScale = 0.001
Chart1.View.AxisY.MinScale = 0.001
'Checking the pressed key
If e.Key = Key.Down Then
Chart1.BeginUpdate()
'Decreasing the scale values in order to ZoomIn
Chart1.View.AxisX.Scale = Chart1.View.AxisX.Scale - 0.35
Chart1.View.AxisY.Scale = Chart1.View.AxisY.Scale - 0.35
UpdateScrollbars()
Chart1.EndUpdate()
ElseIf e.Key = Key.Up Then
Chart1.BeginUpdate()
'Increasing the scale values in order to ZoomOut
Chart1.View.AxisX.scale = Chart1.View.AxisX.Scale + 0.35
Chart1.View.AxisY.Scale = Chart1.View.AxisY.Scale + 0.35
UpdateScrollbars()
Chart1.EndUpdate()
ElseIf e.Key = Key.Escape Then
Chart1.BeginUpdate()
'Setting the Scale to Default Value
Chart1.View.AxisX.Scale = 1
Chart1.View.AxisY.Scale = 1
UpdateScrollbars()
Chart1.EndUpdate()
End If
End Sub
Run the attached samples, press KeyDown/KeyUp and you will observe the following output : Download Sample-C# Download Sample-VB