How to achieve the draggable legend in WPF Chart (SfChart)?
This article describes how to make it possible for end-users to move a chart's legend at runtime in WPF Chart.
To change the position of legend at any arbitrary location inside the chart area, set the DockPosition as Floating with subscribing the necessary mouse events to change their X and Y legend offset as per follows.
[XAML]
<chart:SfChart x:Name="sfChart" MouseMove="SfChart_MouseMove" MouseLeftButtonUp="SfChart_MouseLeftButtonUp"> <chart:SfChart.Legend> <chart:ChartLegend x:Name="legend" DockPosition="Floating" MouseLeftButtonDown="Legend_MouseLeftButtonDown" OffsetX="200"/> </chart:SfChart.Legend> … </chart:SfChart>
[C#]
private bool isDragable = false; private void SfChart_MouseMove(object sender, MouseEventArgs e) { var chart = sender as SfChart; if (isDragable) { var position = e.GetPosition(chart); ChartLegend legend = chart.Legend as ChartLegend; legend.OffsetX = position.X - (chart.SeriesClipRect.Left + legend.DesiredSize.Width / 2); legend.OffsetY = position.Y - (chart.SeriesClipRect.Top + legend.DesiredSize.Height / 2); if ((chart.Legend as ChartLegend).IsMouseOver) { if (Mouse.OverrideCursor == null) Mouse.OverrideCursor = Cursors.Hand; } } } private void SfChart_MouseLeftButtonUP(object sender, MouseButtonEventArgs e) { isDragable = false; } private void Legend_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { isDragable = true; }
Output
For more details, please refer to the project on GitHub.
See Also
How to set or modify the label of each legend
How to add multiple legend items in scroll viewer
How to create custom legend items in WPF SfChart
How to wrap the text in the WPF Chart legend
How to format the legend text in Chart WPF
Conclusion
I hope you enjoyed learning how to achieve the draggable legend in WPF Chart (SfChart)?
You can refer to our WPF Chart feature tour page know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our WPF Chart Examples to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!