How to create a live chart using .NET MAUI Toolkit?
The SfCartesianChart in .NET MAUI supports real-time data updates, making it ideal for applications such as ECG monitors, stock tickers, and live IoT feeds. In this article, you will learn how to create a live-updating ECG chart using FastLineSeries, ObservableCollection, and IDispatcherTimer.
Step 1: Create the Data Model
We start by defining a model class to represent each point in the ECG chart. Each point contains:
- Value: X-axis position (sample index)
- Size: Y-axis value (ECG amplitude)
public class ChartDataModel
{
public double Value { get; set; } // X-axis value (sample index)
public double Size { get; set; } // Y-axis value (ECG amplitude)
}
Step 2: Build the ViewModel
The RealTimeChartViewModel manages the live chart data. It performs the following:
- Maintains an observable data collection (LiveData) bound to the chart
- Uses IDispatcherTimer to simulate new ECG points every 100ms
- Adds new data points while removing the oldest ones to simulate a live scroll
public class RealTimeChartViewModel : INotifyPropertyChanged
{
private ObservableCollection<ChartDataModel> liveData;
private readonly Random randomValue;
private IDispatcherTimer? timer;
private int dataIndex = 0;
private const int maxDataPoints = 100;
public RealTimeChartViewModel()
{
randomValue = new Random();
liveData = new ObservableCollection<ChartDataModel>();
InitializeDataPoints();
}
// Live data bound to the chart.
public ObservableCollection<ChartDataModel> LiveData
{
get => liveData;
set
{
liveData = value;
OnPropertyChanged();
}
}
// Fill the chart with initial dummy data.
private void InitializeDataPoints()
{
LiveData.Clear();
dataIndex = 0;
for (int i = 0; i < maxDataPoints; i++)
{
LiveData.Add(new ChartDataModel
{
Value = i,
Size = GetNextECGValue() // Simulated ECG value
});
dataIndex++;
}
}
// Simulates an ECG waveform using patterns and randomness.
private double GetNextECGValue()
{
double baseValue = 800;
int phase = dataIndex % 20;
// Create a rough ECG shape by applying different value spikes
return phase switch
{
0 => baseValue + randomValue.Next(10, 20),
1 => baseValue - randomValue.Next(50, 100),
2 => baseValue + randomValue.Next(200, 300),
3 => baseValue - randomValue.Next(150, 250),
4 => baseValue + randomValue.Next(50, 100),
5 => baseValue + randomValue.Next(-20, 20)
};
}
/// Starts the update timer (10Hz).
public void StartTimer()
{
if (timer == null)
{
timer = Dispatcher.GetForCurrentThread().CreateTimer();
timer.Interval = TimeSpan.FromMilliseconds(100); // 100ms interval
timer.Tick += Timer_Tick;
timer.Start();
}
}
// Stops the timer when chart is not visible.
public void StopTimer()
{
timer?.Stop();
timer = null;
}
// Called every 100ms to simulate real-time data.
private void Timer_Tick(object? sender, EventArgs e)
{
if (LiveData.Count > 0)
{
// Remove oldest point
LiveData.RemoveAt(0);
// Add new point at the end
LiveData.Add(new ChartDataModel
{
Value = dataIndex++,
Size = GetNextECGValue()
});
}
}
public event PropertyChangedEventHandler? PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
Step 3: Design the Chart in XAML
Create an instance of SfCartesianChart and bind it to the ViewModel with FastLineSeries for efficient real-time data plotting.
<chart:SfCartesianChart>
<chart:SfCartesianChart.BindingContext>
<local:RealTimeChartViewModel x:Name="realTimeChartViewModel"/>
</chart:SfCartesianChart.BindingContext>
.....
<chart:SfCartesianChart.Series>
<chart:FastLineSeries ItemsSource="{Binding LiveData}"
EnableAntiAliasing="True"
XBindingPath="Value"
YBindingPath="Size">
</chart:FastLineSeries>
</chart:SfCartesianChart.Series>
</chart:SfCartesianChart>
Tips and Best Practices
Thread Safety
Use Dispatcher for UI Updates
- MAUI’s IDispatcherTimer ensures updates happen on the UI thread.
- Prevents cross-thread exceptions.
Output:
Download the complete sample from GitHub.
Conclusion:
I hope you enjoyed learning how to create a live chart using .NET MAUI Toolkit?
You can refer to our .NET MAUI Chart’s feature tour page to learn about its other groundbreaking feature representations. You can also explore our .NET MAUI Toolkit Chart documentation to understand how to present and manipulate data.
For current customers, check out our .NET MAUI from the License and Downloads page. If you are new to Syncfusion®, try our 30-day free trial to check out our .NET MAUI Chart and other .NET MAUI components.
Please let us know in the following comments section if you have any queries or require clarifications. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!