Skip to content

Commit

Permalink
Merge pull request #1 from SyncfusionExamples/KB-925774-LabelClickedE…
Browse files Browse the repository at this point in the history
…vent

How to Add Annotation on Axis Label Click in WPF SfChart
  • Loading branch information
Saravanan-Madhesh authored Dec 14, 2024
2 parents 2bbb64f + 13496d9 commit edd0f9c
Show file tree
Hide file tree
Showing 11 changed files with 308 additions and 2 deletions.
103 changes: 101 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,101 @@
# How-to-Add-Annotation-in-Axis-Label-Click-in-WPF-SfChart
Learn how to add an annotation to a WPF SfChart when an axis label is clicked. This functionality enhances the interactivity of your chart by highlighting specific data points and providing additional information.
# How to Add Annotation in Axis Label Click in WPF SfChart?

This article provides a detailed walkthrough on how to add an annotation to a [WPF SfChart](https://www.syncfusion.com/wpf-controls/charts) using [LabelClicked](https://help.syncfusion.com/wpf/charts/axis#labelclicked) event when an axis label is clicked. This functionality enhances the interactivity of your chart by displaying specific information about the clicked label.

Learn step-by-step instructions and gain insights on using the Label Clicked event in a WPF SfChart.

**Step 1:** Initialize the SfChart with Primary and Secondary axes by referring to the WPF charts [documentation](https://help.syncfusion.com/wpf/charts/getting-started). Trigger the [LabelClicked](https://help.syncfusion.com/cr/wpf/Syncfusion.UI.Xaml.Charts.ChartAxisBase2D.html#events) event on the primary axis.

XAML
```xml
<chart:SfChart x:Name="chart">

<chart:SfChart.PrimaryAxis>
<chart:CategoryAxis LabelClicked="Axis_LabelClicked"/>
</chart:SfChart.PrimaryAxis>

<chart:SfChart.SecondaryAxis>
<chart:NumericalAxis/>
</chart:SfChart.SecondaryAxis>

<chart:ColumnSeries ItemsSource="{Binding DataSource}"
XBindingPath="Company"
YBindingPath="Revenue"/>

</chart:SfChart>
```

**Step 2:** Implement the event handler for the **LabelClicked** event of the primary axis. This event handler will be triggered when a label on the primary axis is clicked. The [LabelContent](https://help.syncfusion.com/cr/wpf/Syncfusion.UI.Xaml.Charts.ChartAxisLabel.html#Syncfusion_UI_Xaml_Charts_ChartAxisLabel_LabelContent) and [Position](https://help.syncfusion.com/cr/wpf/Syncfusion.UI.Xaml.Charts.ChartAxisLabel.html#Syncfusion_UI_Xaml_Charts_ChartAxisLabel_Position) of the clicked label can be retrieved from the [AxisLabelClickedEventArgs](https://help.syncfusion.com/cr/wpf/Syncfusion.UI.Xaml.Charts.AxisLabelClickedEventArgs.html).

C#
```csharp
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void Axis_LabelClicked(object sender, AxisLabelClickedEventArgs e)
{
string labelContent = e.AxisLabel.LabelContent.ToString();
int labelPosition = (int)e.AxisLabel.Position;
}
}
```

**Step 3:** Create and add an [Annotation](https://help.syncfusion.com/wpf/charts/annotations) to the chart in the event handler based on the label position obtained from the event arguments. Populate the data list from the ItemsSource to diplay the revenue values.

C#
```csharp
public partial class MainWindow : Window
{
List<double> data = new();

public MainWindow()
{
InitializeComponent();

foreach (var value in viewModel.DataSource)
{
data.Add(value.Revenue);
}
}

private void Axis_LabelClicked(object sender, AxisLabelClickedEventArgs e)
{
string labelContent = e.AxisLabel.LabelContent.ToString();
int labelPosition = (int)e.AxisLabel.Position;

chart.Annotations.Clear();

RectangleAnnotation annotation = new()
{
X1 = labelPosition,
Y1 = data[labelPosition] + 10,
X2 = labelPosition + 1,
Y2 = data[labelPosition] + 110,
CoordinateUnit = CoordinateUnit.Axis,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalTextAlignment = VerticalAlignment.Center,
Text = $"Revenue: {data[labelPosition]} USD",
FontWeight = FontWeights.Bold,
Fill = new SolidColorBrush(Colors.SkyBlue),
Stroke = new SolidColorBrush(Colors.Transparent)
};

chart.Annotations.Add(annotation);
}
}
```

**Step 4:** After deploying the application, click on the axis label as shown in the output below; the annotations will be displayed, showing the values corresponding to the label.

**Output:**
![Presentation1](https://github.com/user-attachments/assets/2cfe0fe0-3e3c-42b1-acca-1ba8b3fab185)

## Troubleshooting
### Path too long exception
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.

For more details, refer to the KB on [How-to-Add-Annotation-in-Axis-Label-Click-in-WPF-SfChart](https://support.syncfusion.com/kb/article/18485/how-to-add-annotation-in-axis-label-click-in-wpf-sfchart).
22 changes: 22 additions & 0 deletions WPFChartLabelEvents/WPFChartLabelEvents.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.12.35506.116 d17.12
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WPFChartLabelEvents", "WPFChartLabelEvents\WPFChartLabelEvents.csproj", "{A0F1EF82-1071-485B-A0BF-F921429BDC23}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A0F1EF82-1071-485B-A0BF-F921429BDC23}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A0F1EF82-1071-485B-A0BF-F921429BDC23}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A0F1EF82-1071-485B-A0BF-F921429BDC23}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A0F1EF82-1071-485B-A0BF-F921429BDC23}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
9 changes: 9 additions & 0 deletions WPFChartLabelEvents/WPFChartLabelEvents/App.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Application x:Class="WPFChartLabelEvents.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFChartLabelEvents"
StartupUri="MainWindow.xaml">
<Application.Resources>

</Application.Resources>
</Application>
14 changes: 14 additions & 0 deletions WPFChartLabelEvents/WPFChartLabelEvents/App.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System.Configuration;
using System.Data;
using System.Windows;

namespace WPFChartLabelEvents
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}

}
10 changes: 10 additions & 0 deletions WPFChartLabelEvents/WPFChartLabelEvents/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using System.Windows;

[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
43 changes: 43 additions & 0 deletions WPFChartLabelEvents/WPFChartLabelEvents/MainWindow.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<Window x:Class="WPFChartLabelEvents.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPFChartLabelEvents"
xmlns:chart="clr-namespace:Syncfusion.UI.Xaml.Charts;assembly=Syncfusion.SfChart.WPF"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">

<Grid>

<chart:SfChart x:Name="chart">

<chart:SfChart.DataContext>
<local:ViewModel x:Name="viewModel"/>
</chart:SfChart.DataContext>

<chart:SfChart.Header>
<TextBlock Text="Leading Tech Companies of 2024" FontSize="24" FontWeight="DemiBold" Margin="5" />
</chart:SfChart.Header>

<chart:SfChart.PrimaryAxis>
<chart:CategoryAxis x:Name="xAxis" LabelClicked="Axis_LabelClicked" ShowGridLines="False">
<chart:CategoryAxis.LabelStyle>
<chart:LabelStyle FontSize="14" FontFamily="Verdana"/>
</chart:CategoryAxis.LabelStyle>
</chart:CategoryAxis>
</chart:SfChart.PrimaryAxis>

<chart:SfChart.SecondaryAxis>
<chart:NumericalAxis x:Name="yAxis" Maximum="800" Interval="100">
<chart:NumericalAxis.LabelStyle>
<chart:LabelStyle FontSize="12" FontFamily="Verdana"/>
</chart:NumericalAxis.LabelStyle>
</chart:NumericalAxis>
</chart:SfChart.SecondaryAxis>

<chart:ColumnSeries ItemsSource="{Binding DataSource}" XBindingPath="Company" YBindingPath="Revenue"/>
</chart:SfChart>

</Grid>
</Window>
49 changes: 49 additions & 0 deletions WPFChartLabelEvents/WPFChartLabelEvents/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System.Windows;
using System.Windows.Media;
using Syncfusion.UI.Xaml.Charts;

namespace WPFChartLabelEvents
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
List<double> data = new();

public MainWindow()
{
InitializeComponent();

foreach (var value in viewModel.DataSource)
{
data.Add(value.Revenue);
}
}

private void Axis_LabelClicked(object sender, AxisLabelClickedEventArgs e)
{
string labelContent = (string)e.AxisLabel.LabelContent;
int labelPosition = (int)e.AxisLabel.Position;

chart.Annotations.Clear();

RectangleAnnotation annotation = new()
{
X1 = labelPosition,
Y1 = data[labelPosition] + 10,
X2 = labelPosition + 1,
Y2 = data[labelPosition] + 110,
CoordinateUnit = CoordinateUnit.Axis,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalTextAlignment = VerticalAlignment.Center,
Text = $"Revenue: {data[labelPosition]} USD",
FontWeight = FontWeights.Bold,
Fill = new SolidColorBrush(Colors.SkyBlue),
Stroke = new SolidColorBrush(Colors.Transparent)
};

chart.Annotations.Add(annotation);
}
}
}
8 changes: 8 additions & 0 deletions WPFChartLabelEvents/WPFChartLabelEvents/Model.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace WPFChartLabelEvents
{
public class Model
{
public required string Company { get; set; }
public double Revenue { get; set; }
}
}
23 changes: 23 additions & 0 deletions WPFChartLabelEvents/WPFChartLabelEvents/ViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System.Collections.ObjectModel;

namespace WPFChartLabelEvents
{
public class ViewModel
{
public ObservableCollection<Model> DataSource { get; set; }

public ViewModel()
{
DataSource = new ObservableCollection<Model>
{
new Model { Company = "Apple", Revenue = 382 },
new Model { Company = "Microsoft", Revenue = 237 },
new Model { Company = "Amazon", Revenue = 591 },
new Model { Company = "Alphabet", Revenue = 318 },
new Model { Company = "Nvidia", Revenue = 200 },
new Model { Company = "Meta", Revenue = 143 },
new Model { Company = "Samsung", Revenue = 201 }
};
}
}
}
15 changes: 15 additions & 0 deletions WPFChartLabelEvents/WPFChartLabelEvents/WPFChartLabelEvents.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net9.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Syncfusion.SfChart.WPF" Version="*" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
<ItemGroup>
<ApplicationDefinition Update="App.xaml">
<SubType>Designer</SubType>
</ApplicationDefinition>
</ItemGroup>
<ItemGroup>
<Page Update="MainWindow.xaml">
<SubType>Designer</SubType>
</Page>
</ItemGroup>
</Project>

0 comments on commit edd0f9c

Please sign in to comment.