Skip to content

Commit a591395

Browse files
Merge pull request #1 from SyncfusionExamples/KB-917142-SfChartMultipleTrackballs
Task- 917142 Added the sample for multiple trackball
2 parents af8e472 + 0e8498f commit a591395

File tree

11 files changed

+620
-1
lines changed

11 files changed

+620
-1
lines changed

README.md

Lines changed: 233 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,233 @@
1-
# How to add multiple trackballs in a WPF SfChart.
1+
# How to add multiple trackballs in a WPF SfChart.
2+
This article provides a detailed walkthrough on how to add multiple trackballs in an [SfChart](https://help.syncfusion.com/wpf/charts/getting-started) in WPF, allowing you to hover over the trackball with your mouse and move them independently to view the information of different data points simultaneously.
3+
4+
Learn step-by-step instructions and gain insights to add multiple trackballs in a WPF SfChart.
5+
6+
**Step 1:** Initialize the SfChart with primary and secondary axes. For more detailed steps, refer to the WPF Charts [documentation](https://help.syncfusion.com/wpf/charts/getting-started).
7+
8+
XAML
9+
10+
```XML
11+
<Grid>
12+
13+
<chart:SfChart x:Name="chart">
14+
15+
<chart:SfChart.PrimaryAxis>
16+
<chart:CategoryAxis/>
17+
</chart:SfChart.PrimaryAxis>
18+
19+
<chart:SfChart.SecondaryAxis>
20+
<chart:NumericalAxis/>
21+
</chart:SfChart.SecondaryAxis>
22+
23+
<chart:LineSeries ItemsSource="{Binding Data}"
24+
XBindingPath="Day"
25+
YBindingPath="CPULoad" >
26+
</chart:LineSeries>
27+
28+
</chart:SfChart>
29+
30+
</Grid>
31+
```
32+
33+
**Step 2:** Create a custom ChartTrackBallBehaviorExt class, which is inherited from [ChartTrackballBehavior](https://help.syncfusion.com/cr/wpf/Syncfusion.UI.Xaml.Charts.ChartTrackBallBehavior.html#).
34+
35+
C#
36+
37+
```csharp
38+
public class ChartTrackBallBehaviorExt : ChartTrackBallBehavior
39+
{
40+
41+
}
42+
```
43+
44+
**Step 3:** Create instances of ChartTrackBallBehaviorExt, and add them to the [Behaviors](https://help.syncfusion.com/cr/wpf/Syncfusion.UI.Xaml.Charts.SfChart.html#Syncfusion_UI_Xaml_Charts_SfChart_Behaviors) collection, assigning specific names to each.
45+
46+
XAML
47+
48+
```XML
49+
<chart:SfChart.Behaviors>
50+
<local:ChartTrackBallBehaviorExt x:Name="trackball1"/>
51+
<local:ChartTrackBallBehaviorExt x:Name="trackball2"/>
52+
</chart:SfChart.Behaviors>
53+
```
54+
55+
**Step 4:** Implement the **ChartTrackBallBehaviorExt** class and its functionalities. Include the **Display** method, which is responsible for displaying the trackball at specified coordinates by setting the IsActivated protected property of the ChartTrackBallBehavior class. Manage multiple trackballs by overriding **mouse event handlers** in ChartTrackBallBehavior, using the **FindNearestTrackball** method in **OnMouseEnter** to locate the closest trackball. The **isTrackballActive** variable ensures only the active trackball responds to the events.
56+
57+
C#
58+
59+
```csharp
60+
public class ChartTrackBallBehaviorExt : ChartTrackBallBehavior
61+
{
62+
private bool isTrackballActive = false;
63+
64+
public SfChart? SfChart { get; set; }
65+
66+
public double X { get; set; }
67+
public double Y { get; set; }
68+
69+
protected override void OnMouseEnter(MouseEventArgs e)
70+
{
71+
// Get the position of the mouse pointer
72+
var touchPoint = e.GetPosition(null);
73+
74+
// Find the nearest trackball to the mouse pointer
75+
var trackball = FindNearestTrackball(touchPoint);
76+
77+
// Activate the trackball if it is the nearest one
78+
if (trackball == this)
79+
{
80+
isTrackballActive = true;
81+
base.OnMouseEnter(e);
82+
}
83+
}
84+
85+
protected override void OnMouseMove(MouseEventArgs e)
86+
{
87+
// Check if the trackball is activated
88+
if (isTrackballActive)
89+
{
90+
// Get the position of the mouse pointer
91+
var touchPoint = e.GetPosition(null);
92+
93+
// Display the trackball at the current mouse position
94+
Display((float)touchPoint.X, (float)touchPoint.Y);
95+
base.OnMouseMove(e);
96+
}
97+
}
98+
99+
protected override void OnMouseLeave(MouseEventArgs e)
100+
{
101+
// Deactivate the trackball
102+
isTrackballActive = false;
103+
}
104+
105+
private ChartTrackBallBehavior FindNearestTrackball(Point touchPoint)
106+
{
107+
ChartTrackBallBehavior nearestTrackball = new ChartTrackBallBehaviorExt();
108+
double minDistance = double.MaxValue;
109+
110+
// Iterate through all trackball behaviors to find the nearest one
111+
if (SfChart != null)
112+
{
113+
foreach (var trackballBehaviour in SfChart.Behaviors)
114+
{
115+
if (trackballBehaviour is ChartTrackBallBehaviorExt trackball)
116+
{
117+
// Calculate the distance between the trackball and the touch point
118+
double distance = Math.Sqrt(Math.Pow(trackball.X - touchPoint.X, 2) + Math.Pow(trackball.Y - touchPoint.Y, 2));
119+
120+
// Update the nearest trackball if the current one is closer
121+
if (distance < minDistance)
122+
{
123+
minDistance = distance;
124+
nearestTrackball = trackball;
125+
}
126+
}
127+
}
128+
}
129+
return nearestTrackball;
130+
}
131+
132+
public void Display(float x, float y)
133+
{
134+
X = x; Y = y;
135+
IsActivated = true;
136+
var point = new Point(x, y);
137+
138+
// Set the internal property for the current point
139+
SetInternalProperty(typeof(ChartTrackBallBehavior), this, point, "CurrentPoint");
140+
141+
// Trigger the pointer position changed event
142+
base.OnPointerPositionChanged();
143+
144+
// Activate the trackball
145+
InvokeInternalMethod(typeof(ChartTrackBallBehavior), this, "Activate", IsActivated);
146+
}
147+
148+
// Sets an internal property of an object using reflection.
149+
internal static void SetInternalProperty(Type type, object obj, object value, string propertyName)
150+
{
151+
var properties = type.GetRuntimeProperties();
152+
153+
foreach (var item in properties)
154+
{
155+
if (item.Name == propertyName)
156+
{
157+
item.SetValue(obj, value);
158+
break;
159+
}
160+
}
161+
}
162+
163+
// Invokes an internal method of an object using reflection.
164+
internal static object? InvokeInternalMethod(Type type, object obj, string methodName, params object[] args)
165+
{
166+
var method = type.GetTypeInfo().GetDeclaredMethod(methodName);
167+
return method?.Invoke(obj, args);
168+
}
169+
}
170+
```
171+
172+
**Step 5:** Assign the chart instance to the **SfChart** property in the **ChartTrackBallBehaviorExt** class, and override the **OnContentRendered** method to run the asynchronous task that calls **ShowTrackball** method.
173+
174+
The **ShowTrackballMethod** method calculates the positions and displays the trackballs on the chart.
175+
176+
C#
177+
178+
```csharp
179+
public partial class MainWindow : Window
180+
{
181+
public MainWindow()
182+
{
183+
InitializeComponent();
184+
trackball1.SfChart = this.chart;
185+
trackball2.SfChart = this.chart;
186+
}
187+
188+
protected override void OnContentRendered(EventArgs e)
189+
{
190+
base.OnContentRendered(e);
191+
192+
// Run the ShowTrackball method asynchronously
193+
Task.Run(async () =>
194+
{
195+
await ShowTrackball();
196+
});
197+
}
198+
199+
async Task ShowTrackball()
200+
{
201+
// Wait for 1 second before executing the rest of the method
202+
await Task.Delay(1000);
203+
Application.Current.Dispatcher.Invoke(() =>
204+
{
205+
// Calculated positions for the first trackball
206+
float xPosition = (float)chart.ValueToPoint(chart.PrimaryAxis, 1);
207+
float yPosition = (float)chart.ValueToPoint(chart.SecondaryAxis, 169);
208+
209+
// Calculated positions for the second trackball
210+
float xPosition1 = (float)chart.ValueToPoint(chart.PrimaryAxis, 6);
211+
float yPosition1 = (float)chart.ValueToPoint(chart.SecondaryAxis, 170);
212+
213+
// Display the first trackball
214+
trackball1.Display(xPosition, yPosition);
215+
216+
// Display the second trackball
217+
trackball2.Display(xPosition1, yPosition1);
218+
});
219+
}
220+
}
221+
```
222+
223+
**Step 6:** To control the trackballs, simply hover over them with your mouse. As you move the mouse within the chart area, the trackball will follow the cursor, allowing you to inspect different data points interactively.
224+
225+
**Output:**
226+
227+
![trackball_demo](https://github.com/user-attachments/assets/2d319594-8d8c-49f1-be27-5d9573b45344)
228+
229+
## Troubleshooting
230+
### Path too long exception
231+
If you are facing a path too long exception when building this example project, close Visual Studio and rename the repository to short and build the project.
232+
233+
For more details, refer to the KB on [How to add multiple trackballs in a WPF SfChart?](https://support.syncfusion.com/kb/article/17741/how-to-add-multiple-trackballs-in-a-wpf-sfchart).
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio Version 17
4+
VisualStudioVersion = 17.11.35327.3
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SfChartMultipleTrackball", "SfChartMultipleTrackball\SfChartMultipleTrackball.csproj", "{E5B30519-D065-42FC-B89A-B435C07011D9}"
7+
EndProject
8+
Global
9+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
10+
Debug|Any CPU = Debug|Any CPU
11+
Release|Any CPU = Release|Any CPU
12+
EndGlobalSection
13+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
14+
{E5B30519-D065-42FC-B89A-B435C07011D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15+
{E5B30519-D065-42FC-B89A-B435C07011D9}.Debug|Any CPU.Build.0 = Debug|Any CPU
16+
{E5B30519-D065-42FC-B89A-B435C07011D9}.Release|Any CPU.ActiveCfg = Release|Any CPU
17+
{E5B30519-D065-42FC-B89A-B435C07011D9}.Release|Any CPU.Build.0 = Release|Any CPU
18+
EndGlobalSection
19+
GlobalSection(SolutionProperties) = preSolution
20+
HideSolutionNode = FALSE
21+
EndGlobalSection
22+
GlobalSection(ExtensibilityGlobals) = postSolution
23+
SolutionGuid = {0CA07FB0-0F65-49F3-AFCC-11C28CE1D119}
24+
EndGlobalSection
25+
EndGlobal
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<Application x:Class="SfChartMultipleTrackball.App"
2+
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3+
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4+
xmlns:local="clr-namespace:SfChartMultipleTrackball"
5+
StartupUri="MainWindow.xaml">
6+
<Application.Resources>
7+
8+
</Application.Resources>
9+
</Application>
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
using System.Configuration;
2+
using System.Data;
3+
using System.Windows;
4+
5+
namespace SfChartMultipleTrackball
6+
{
7+
/// <summary>
8+
/// Interaction logic for App.xaml
9+
/// </summary>
10+
public partial class App : Application
11+
{
12+
}
13+
14+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
using System.Windows;
2+
3+
[assembly: ThemeInfo(
4+
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
5+
//(used if a resource is not found in the page,
6+
// or application resource dictionaries)
7+
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
8+
//(used if a resource is not found in the page,
9+
// app, or any theme specific resource dictionaries)
10+
)]

0 commit comments

Comments
 (0)