Getting Started with WPF Sparkline (SfSparkline)
18 Jul 20243 minutes to read
Creating sparkline
Following steps explain how to create sparkline,
Adding the assembly reference:
- Open the Add Reference window from your project.
- Choose Assemblies -> Extensions -> Syncfusion.SfChart.WPF
- Add the following namespace in your XAML page:
xmlns:Syncfusion="clr-namespace:Syncfusion.UI.Xaml.Charts"
using Syncfusion.UI.Xaml.Charts;
NOTE
This window differs for the Visual Basic project.
Initialize the sparkline
You need to initialize the sparkline represented by the following class Syncfusion.UI.Xaml.Charts.SfChart,
<Syncfusion:SfLineSparkline>
</Syncfusion:SfLineSparkline>
SfLineSparkline sparkline = new SfLineSparkline()
Create a Sample Data Source
Since the above step will produce only an empty sparkline, we need to add some data to the sparkline for plotting. In this step, let’s create a sample data source.
public class UserProfile
{
public DateTime TimeStamp { get; set; }
public double NoOfUsers { get; set; }
}
public class UsersViewModel
{
public UsersViewModel()
{
this.UsersList = new ObservableCollection<UserProfile>();
DateTime date = DateTime.Today;
UsersList.Add(new UserProfile { TimeStamp = date.AddHours(0.5), NoOfUsers = 3000 });
UsersList.Add(new UserProfile { TimeStamp = date.AddHours(0.5), NoOfUsers = 5000 });
UsersList.Add(new UserProfile { TimeStamp = date.AddHours(0.5), NoOfUsers = -3000 });
UsersList.Add(new UserProfile { TimeStamp = date.AddHours(0.5), NoOfUsers = -4000 });
UsersList.Add(new UserProfile { TimeStamp = date.AddHours(0.5), NoOfUsers = 2000 });
UsersList.Add(new UserProfile { TimeStamp = date.AddHours(0.5), NoOfUsers = 3000 }); }
public ObservableCollection<UserProfile> UsersList
{
get; set;
}
}
NOTE
Syncfusion sparkline also supports items source as collection of double values and collection inherited from IEnumerable.
Binding Data to sparkline
We need to add the above UsersViewModel to the DataContext of the sparkline, bind the data source to the ItemsSource property of the SfLineSparkline, and then map the data using YBindingPath and XBindingPath.
<Grid.DataContext>
<local:UsersViewModel/>
</Grid.DataContext>
<Syncfusion:SfLineSparkline
ItemsSource="{Binding UsersList}"
YBindingPath="NoOfUsers">
</Syncfusion:SfLineSparkline >
SfLineSparkline sparkline = new SfLineSparkline()
{
ItemsSource = new SparkViewModel().UsersList,
YBindingPath = "NoOfUsers"
};
NOTE
if we do not map the XBindingPath means sparkline data positioned as indexed.
The following illustrates the result of the above code sample,
Theme
SfSparkline supports various built-in themes. Refer to the below links to apply themes for the SfSparkline,