We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

How to achieve the draggable legend in WPF Chart (SfChart)?

Platform: WPF |
Control: SfChart

This article describes how to make it possible for end-users to move a chart's legend at runtime.

 

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

Drag the legend in WPF Chart


Download the complete sample here.

 

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

2X faster development

The ultimate WPF UI toolkit to boost your development speed.
ADD COMMENT
You must log in to leave a comment

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile