SciChart® the market leader in Fast WPF Charts, WPF 3D Charts, and iOS Chart & Android Chart Components
SciChart WPF ships with hundreds of WPF Chart Examples which you can browse, play with, view the source-code and even export each WPF Chart Example to a stand-alone Visual Studio solution. All of this is possible with the new and improved SciChart WPF Examples Suite, which ships as part of the SciChart WPF SDK.
This examples showcases the performance of SciChart when rendering a real-time FIFO chart on 50 SciChartSurface instances at the same time.
SciChartSurface controls are loaded in an ItemsControl (using DataTemplates, MVVM) and bound to a real-time source of data. The data is pushed in at a phenomenal rate and the chart updates in real-time.
The scrolling effect is achieved by using FIFO Dataseries, which automatically discard old points once a threshold is met. Useful for ECG style monitoring applications!
Documentation Links
The C#/WPF source code for the WPF Chart 50-Channel EEG example is included below (Scroll down!).
Did you know you can also view the source code from one of the following sources as well?
<UserControl x:Class="SciChart.Examples.Examples.CreateRealtimeChart.EEGChannelsDemo.EEGExampleView" 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:ext="http://schemas.abtsoftware.co.uk/scichart/exampleExternals" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:s="http://schemas.abtsoftware.co.uk/scichart" d:DesignHeight="400" d:DesignWidth="600" mc:Ignorable="d"> <i:Interaction.Triggers> <i:EventTrigger EventName="Loaded"> <i:InvokeCommandAction Command="{Binding StartCommand}" /> </i:EventTrigger> <i:EventTrigger EventName="Unloaded"> <i:InvokeCommandAction Command="{Binding StopCommand}" /> </i:EventTrigger> </i:Interaction.Triggers> <UserControl.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/SciChart.Examples.ExternalDependencies;component/Resources/Styles/MergedResources.xaml" /> <ResourceDictionary Source="/SciChart.Examples.ExternalDependencies;component/Resources/Styles/ToolbarButtonsCommon.xaml" /> </ResourceDictionary.MergedDictionaries> <!-- ItemTemplate for EEG Channels. Create a single SciChartSurface instance per EEGChannelViewModel --> <DataTemplate x:Key="ChannelItemTemplate"> <Grid IsHitTestVisible="False"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" SharedSizeGroup="Name" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <TextBlock Margin="10,0" Foreground="White" Text="{Binding ChannelName}" /> <!-- Declare the SciChartSurface. We use RenderPriority=Low to put rendering below mouse input and keep the app responsive --> <s:SciChartSurface Grid.Column="1" Height="20" HorizontalAlignment="Stretch" Padding="0"> <!-- Declare RenderableSeries, which are mapped to DataSet Series 1:1 and in order --> <s:SciChartSurface.RenderableSeries> <s:FastLineRenderableSeries AntiAliasing="False" DataSeries="{Binding ChannelDataSeries}" ResamplingMode="None" Stroke="{Binding Stroke, Mode=OneWay}"> <s:FastLineRenderableSeries.RolloverMarkerTemplate> <ControlTemplate> <Ellipse Width="7" Height="7" Fill="White" /> </ControlTemplate> </s:FastLineRenderableSeries.RolloverMarkerTemplate> </s:FastLineRenderableSeries> </s:SciChartSurface.RenderableSeries> <!-- Axes are created implicitly when a dataset is created, but we override them here so we can style them --> <s:SciChartSurface.XAxis> <s:NumericAxis AutoRange="Always" DrawMajorGridLines="False" DrawMinorGridLines="False" DrawMajorBands="False" Visibility="Collapsed"> <s:NumericAxis.GrowBy> <s:DoubleRange Max="0" Min="0" /> </s:NumericAxis.GrowBy> </s:NumericAxis> </s:SciChartSurface.XAxis> <s:SciChartSurface.YAxis> <s:NumericAxis AutoRange="Always" DrawMajorGridLines="False" DrawMinorGridLines="False" DrawMajorBands="False" Visibility="Collapsed" /> </s:SciChartSurface.YAxis> </s:SciChartSurface> </Grid> </DataTemplate> <!-- Style per ListBoxItem to ensure the chart stretches to fit --> <Style x:Key="ChannelListBoxItemStyle" TargetType="ListBoxItem"> <Setter Property="HorizontalContentAlignment" Value="Stretch" /> <Setter Property="Margin" Value="3,0,3,0"/> <Setter Property="Padding" Value="0"/> </Style> <!-- Style for Stats --> <Style x:Key="StatsStyle" TargetType="TextBlock"> <Setter Property="FontSize" Value="26" /> <Setter Property="Margin" Value="0" /> <Setter Property="FontWeight" Value="Normal" /> <Setter Property="Foreground" Value="#BBFC9C29" /> <Setter Property="FontFamily" Value="/Resources/Fonts/#Neuropol Regular" /> </Style> <s:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" /> </ResourceDictionary> </UserControl.Resources> <Grid x:Name="LayoutRoot"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Border Panel.ZIndex="9999" Background="#FF232426" BorderBrush="#323539" BorderThickness="0,0,2,0"> <WrapPanel HorizontalAlignment="Right" Orientation="Vertical"> <!-- Define the Toolbar --> <ToggleButton Command="{Binding StartCommand}" Content="Play" Style="{StaticResource PlayButtonStyle}" ToolTip="Play" s:ToggleButtonExtensions.GroupName="RealTimeEEG" /> <ToggleButton Command="{Binding StopCommand}" x:Name="StopButton" Content="Pause" Style="{StaticResource PauseButtonStyle}" ToolTip="Pause" s:ToggleButtonExtensions.GroupName="RealTimeEEG" /> <ToggleButton Command="{Binding ResetCommand}" x:Name="ResetButton" Content="Stop" Style="{StaticResource StopButtonStyle}" ToolTip="Stop" s:ToggleButtonExtensions.GroupName="RealTimeEEG" /> <ext:FlyoutMenuButton x:Name="IntervalFlyoutMenuButton" HorizontalAlignment="Left" Content="Interval" Style="{StaticResource FlyoutMenuButtonStyle}" ToolTipService.ToolTip="Interval (ms)"> <ext:FlyoutMenuButton.PopupContent> <StackPanel MinWidth="150" Orientation="Vertical"> <TextBlock Margin="3" HorizontalAlignment="Left" Foreground="White" Text="Interval (ms): " /> <Slider MinWidth="100" DataContext="{Binding}" IsEnabled="{Binding IsRunning, Converter={StaticResource BooleanToVisibilityConverter}, ConverterParameter=INVERSE}" Maximum="100" Minimum="10" Value="{Binding TimerInterval, Mode=TwoWay}"> <ToolTipService.ToolTip> <StackPanel Orientation="Horizontal"> <TextBlock Foreground="#222222" Text="{Binding TimerInterval}" /> <TextBlock Foreground="#222222" Text=" ms" /> </StackPanel> </ToolTipService.ToolTip> </Slider> </StackPanel> </ext:FlyoutMenuButton.PopupContent> </ext:FlyoutMenuButton> <ext:FlyoutMenuButton x:Name="PointsFlyoutMenuButton" HorizontalAlignment="Left" Content="Points" Style="{StaticResource FlyoutMenuButtonStyle}" ToolTipService.ToolTip="Points per Tick"> <ext:FlyoutMenuButton.PopupContent> <StackPanel MinWidth="150" Orientation="Vertical"> <TextBlock Margin="3" VerticalAlignment="Center" Foreground="White" Text="Points per Tick: " /> <Slider MinWidth="100" DataContext="{Binding}" IsEnabled="{Binding IsRunning, Converter={StaticResource BooleanToVisibilityConverter}, ConverterParameter=INVERSE}" Maximum="100" Minimum="10" Value="{Binding BufferSize, Mode=TwoWay}"> <ToolTipService.ToolTip> <StackPanel Orientation="Horizontal"> <TextBlock Foreground="#222222" Text="{Binding BufferSize}" /> <TextBlock Foreground="#222222" Text=" Points/Tick" /> </StackPanel> </ToolTipService.ToolTip> </Slider> </StackPanel> </ext:FlyoutMenuButton.PopupContent> </ext:FlyoutMenuButton> </WrapPanel> </Border> <!-- Define the listbox which will host the N channels of the EEG --> <ListBox Grid.Column="1" Background="#1c1c1e" BorderThickness="0" ItemContainerStyle="{StaticResource ChannelListBoxItemStyle}" ItemTemplate="{StaticResource ChannelItemTemplate}" ItemsSource="{Binding ChannelViewModels}" Grid.IsSharedSizeScope="True" ScrollViewer.HorizontalScrollBarVisibility="Disabled" /> <!-- Define the Stats Panel --> <Grid Grid.Column="1" Margin="40,40,0,0" HorizontalAlignment="Left" VerticalAlignment="Top"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="60" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <TextBlock Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Top" Style="{StaticResource StatsStyle}" Text="FPS: " /> <TextBlock Name="fpsCounter" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Top" Style="{StaticResource StatsStyle}" /> <TextBlock Grid.Column="2" Margin="10,0,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Style="{StaticResource StatsStyle}" Text="Point Count: " /> <TextBlock Name="pointCount" Grid.Column="3" HorizontalAlignment="Left" VerticalAlignment="Top" Style="{StaticResource StatsStyle}" /> </Grid> </Grid> </UserControl>
// ************************************************************************************* // SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved. // // Web: http://www.scichart.com // Support: support@scichart.com // Sales: sales@scichart.com // // EEGExampleView.xaml.cs is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. // ************************************************************************************* using System; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using SciChart.Examples.ExternalDependencies.Data; namespace SciChart.Examples.Examples.CreateRealtimeChart.EEGChannelsDemo { /// <summary> /// Interaction logic for EEGExampleView.xaml /// </summary> public partial class EEGExampleView : UserControl { private Stopwatch _stopWatch; private double _lastFrameTime; private MovingAverage _fpsAverage; public EEGExampleView() { InitializeComponent(); _stopWatch = Stopwatch.StartNew(); _fpsAverage = new MovingAverage(5); this.Loaded += OnLoaded; this.Unloaded += OnUnloaded; } private void OnUnloaded(object sender, RoutedEventArgs routedEventArgs) { CompositionTarget.Rendering -= CompositionTarget_Rendering; } private void OnLoaded(object sender, RoutedEventArgs routedEventArgs) { CompositionTarget.Rendering -= CompositionTarget_Rendering; CompositionTarget.Rendering += CompositionTarget_Rendering; } /// <summary> /// Purely for stats reporting (FPS). Not needed for SciChart rendering /// </summary> private void CompositionTarget_Rendering(object sender, EventArgs e) { if (StopButton.IsChecked != true && ResetButton.IsChecked != true) { // Compute the render time double frameTime = _stopWatch.ElapsedMilliseconds; double delta = frameTime - _lastFrameTime; double fps = 1000.0 / delta; // Push the fps to the movingaverage, we want to average the FPS to get a more reliable reading _fpsAverage.Push(fps); // Render the fps to the screen fpsCounter.Text = double.IsNaN(_fpsAverage.Current) ? "-" : string.Format("{0:0}", _fpsAverage.Current); // Render the total point count (all series) to the screen var eegExampleViewModel = (DataContext as EEGExampleViewModel); pointCount.Text = eegExampleViewModel != null ? eegExampleViewModel.PointCount.ToString() : "Na"; _lastFrameTime = frameTime; } } } }
// ************************************************************************************* // SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved. // // Web: http://www.scichart.com // Support: support@scichart.com // Sales: sales@scichart.com // // EEGExampleViewModel.cs is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. // ************************************************************************************* using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Timers; using System.Windows.Input; using System.Windows.Media; using SciChart.Charting.Common.Helpers; using SciChart.Core.Utility; using SciChart.Examples.ExternalDependencies.Common; namespace SciChart.Examples.Examples.CreateRealtimeChart.EEGChannelsDemo { public class EEGExampleViewModel : BaseViewModel { private ObservableCollection<EEGChannelViewModel> _channelViewModels; private readonly IList<Color> _colors = new[] { Colors.White, Colors.Yellow, Color.FromArgb(255, 0, 128, 128), Color.FromArgb(255, 176, 196, 222), Color.FromArgb(255, 255, 182, 193), Colors.Purple, Color.FromArgb(255, 245, 222, 179),Color.FromArgb(255, 173, 216, 230), Color.FromArgb(255, 250, 128, 114), Color.FromArgb(255, 144, 238, 144), Colors.Orange, Color.FromArgb(255, 192, 192, 192), Color.FromArgb(255, 255, 99, 71), Color.FromArgb(255, 205, 133, 63), Color.FromArgb(255, 64, 224, 208), Color.FromArgb(255, 244, 164, 96) }; private readonly Random _random = new Random(); private const int ChannelCount = 50; // Number of channels to render private const int Size = 1000; // Size of each channel in points (FIFO Buffer) private volatile int _currentSize = 0; private uint _timerInterval = 20;// Interval of the timer to generate data in ms private int _bufferSize = 15; // Number of points to append to each channel each timer tick private Timer _timer; private object _syncRoot = new object(); // X, Y buffers used to buffer data into the Scichart instances in blocks of BufferSize private double[] xBuffer; private double[] yBuffer; private bool _running; private bool _isReset; private readonly ActionCommand _startCommand; private readonly ActionCommand _stopCommand; private readonly ActionCommand _resetCommand; private TimedMethod _startDelegate; public EEGExampleViewModel() { _startCommand = new ActionCommand(Start, () => !IsRunning); _stopCommand = new ActionCommand(Stop, () => IsRunning); _resetCommand = new ActionCommand(Reset, () => !IsRunning && !IsReset); } public ObservableCollection<EEGChannelViewModel> ChannelViewModels { get { return _channelViewModels; } set { _channelViewModels = value; OnPropertyChanged("ChannelViewModels"); } } public ICommand StartCommand { get { return _startCommand; } } public ICommand StopCommand { get { return _stopCommand; } } public ICommand ResetCommand { get { return _resetCommand; } } public int PointCount { get { return _currentSize * ChannelCount; } } public double TimerInterval { get { return _timerInterval; } set { _timerInterval = (uint)value; OnPropertyChanged("TimerInterval"); Stop(); } } public double BufferSize { get { return _bufferSize; } set { _bufferSize = (int)value; OnPropertyChanged("BufferSize"); Stop(); } } public bool IsReset { get { return _isReset; } set { _isReset = value; _startCommand.RaiseCanExecuteChanged(); _stopCommand.RaiseCanExecuteChanged(); _resetCommand.RaiseCanExecuteChanged(); OnPropertyChanged("IsReset"); } } public bool IsRunning { get { return _running; } set { _running = value; _startCommand.RaiseCanExecuteChanged(); _stopCommand.RaiseCanExecuteChanged(); _resetCommand.RaiseCanExecuteChanged(); OnPropertyChanged("IsRunning"); } } private void Start() { if (_channelViewModels == null || _channelViewModels.Count == 0) { Reset(); } if (!IsRunning) { IsRunning = true; IsReset = false; xBuffer = new double[_bufferSize]; yBuffer = new double[_bufferSize]; _timer = new Timer(_timerInterval); _timer.Elapsed += OnTick; _timer.AutoReset = true; _timer.Start(); } } private void Stop() { if (IsRunning) { _timer.Stop(); IsRunning = false; } } private void Reset() { Stop(); // Initialize N EEGChannelViewModels. Each of these will be represented as a single channel // of the EEG on the view. One channel = one SciChartSurface instance ChannelViewModels = new ObservableCollection<EEGChannelViewModel>(); for (int i = 0; i < ChannelCount; i++) { var channelViewModel = new EEGChannelViewModel(Size, _colors[i%16]) {ChannelName = "Channel " + i}; ChannelViewModels.Add(channelViewModel); } IsReset = true; } private void OnTick(object sender, EventArgs e) { // Ensure only one timer Tick processed at a time lock (_syncRoot) { for (int i = 0; i < _channelViewModels.Count; i++) { // Get the dataseries created for this channel var channel = _channelViewModels[i]; var dataseries = channel.ChannelDataSeries; // Preload previous value with k-1 sample, or 0.0 if the count is zero double xValue = dataseries.Count > 0 ? dataseries.XValues[dataseries.Count - 1] : 0.0; // Add points 10 at a time for efficiency for (int j = 0; j < BufferSize; j++) { // Generate a new X,Y value in the random walk xValue = xValue + 1; double yValue = _random.NextDouble(); xBuffer[j] = xValue; yBuffer[j] = yValue; } // Append block of values dataseries.Append(xBuffer, yBuffer); // For reporting current size to GUI _currentSize = dataseries.Count; } } } } }
// ************************************************************************************* // SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved. // // Web: http://www.scichart.com // Support: support@scichart.com // Sales: sales@scichart.com // // EEGChannelViewModel.cs is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. // ************************************************************************************* using System.Windows.Media; using SciChart.Charting.Model.DataSeries; using SciChart.Examples.ExternalDependencies.Common; namespace SciChart.Examples.Examples.CreateRealtimeChart.EEGChannelsDemo { public class EEGChannelViewModel : BaseViewModel { private readonly int _size; private Color _color; private IXyDataSeries<double, double> _channelDataSeries; public EEGChannelViewModel(int size, Color color) { _size = size; Stroke = color; // Add an empty First In First Out series. When the data reaches capacity (int size) then old samples // will be pushed out of the series and new appended to the end. This gives the appearance of // a scrolling chart window ChannelDataSeries = new XyDataSeries<double, double>() {FifoCapacity = _size}; // Pre-fill with NaN up to size. This stops the stretching effect when Fifo series are filled with AutoRange for(int i = 0; i < _size; i++) ChannelDataSeries.Append(i, double.NaN); } public string ChannelName { get; set; } public Color Stroke { get { return _color; } set { _color = value; OnPropertyChanged("Stroke"); } } public IXyDataSeries<double, double> ChannelDataSeries { get { return _channelDataSeries; } set { _channelDataSeries = value; OnPropertyChanged("ChannelDataSeries"); } } public void Reset() { _channelDataSeries.Clear(); } } }