Skip to content

To create WPF Chart sample for getting the draggable legend

Notifications You must be signed in to change notification settings

SyncfusionExamples/How-to-drag-the-legend-to-the-WPF-Chart-

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 

Repository files navigation

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

This example demonstrates 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

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

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

About

To create WPF Chart sample for getting the draggable legend

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages