Pre loader

Tag: MVVM

Welcome to the SciChart Forums!

  • Please read our Question Asking Guidelines for how to format a good question
  • Some reputation is required to post answers. Get up-voted to avoid the spam filter!
  • We welcome community answers and upvotes. Every Q&A improves SciChart for everyone

WPF Forums | JavaScript Forums | Android Forums | iOS Forums

0 votes
11k views

Hello support team,

We have to realize the following request:
– Yt chart with DateTime as X-axis and double values on the Y-axis
– The chart should display a user-defined area on startup (e.g. 20 sec) After the chart has run for 20 seconds ( i.e. 20 seconds), the animated scrolling should start. By default, the chart behaves as follows: The X-axis area fills up to 20 seconds and then starts scrolling. We want the chart to display 20 seconds on the X-axis at the start and fill up.

I am aware that I can implement this behavior myself. However, the question arises whether I can realize this directly with a basic functionality.

Thank you!

0 votes
15k views

How can I apply my style and template to my axes if I created the axes as NumericAxisViewModel in code and bound them to my SciChartSurface in my xaml view?

Regards,
Roland

  • Roland D asked 5 years ago
  • last active 2 years ago
0 votes
8k views

When I select a series/plot, I would like to identify where it came with more than just the Name member. How can I do that?

Background:
I have a list of unsigned integer values taken from a data logger. I bundle the values up in a class with some other information, such as the name of the sample and an ID string.

Since I can’t data bind to the logged samples as-is, I convert them to a SciChart friendly “LineRenderableSeriesViewModel” and add them to a list of “ObservableCollection” that I data bind to a SciChart.

ViewModel.cs:

// Where "loggedSamples" is a SamplesContainer 
//class SamplesContainer
//{
//    public string Name;
//    public string ID;  **<=== I want to get this somehow when I select something**
//    public Uint16 data {get;set;}
//}

// Convert Samples => XyDataSeries => LineRenderableSeriesViewModel

SamplesContainer loggedSamples = GetLoggedSample();
XyDataSeries<double, double> xySeries = ConvertSamplesToXyDataSeries(loggedSamples);
xySeries.SeriesName = loggedSamples.Name;

LineRenderableSeriesViewModel lineSeries = new LineRenderableSeriesViewModel() {
    DataSeries = xySeries, StyleKey = "LineStyle", Stroke = Colors.Blue };

RenderableSeriesViewModelForChannels.Add(lineSeries);

MainWindow.xaml:

   <s:SciChartSurface Name="sciChartItemView" Grid.Column="2"
    AllowDrop="True"
    DragDrop.Drop="sciChartItemView_Drop"
    DragDrop.DragEnter="sciChartItemView_DragEnter"
    MinHeight="80"
    s:ThemeManager.Theme="BrightSpark"  
    RenderableSeries="{s:SeriesBinding RenderableSeriesViewModelForChannels}"
    ViewportManager="{Binding SampleSetViewMod.ViewportManager}"                                                                           
    DebugWhyDoesntSciChartRender="True"
    s:SciChartGroup.VerticalChartGroup="sharedYAxisWidth"
    >

    <s:SciChartSurface.XAxis>
        <s:NumericAxis   
        DrawMajorGridLines="True"
        DrawMinorGridLines="False"
        DrawMajorBands="False"  
        VisibleRange="{Binding SampleSetViewMod.SharedXVisibleRange, Mode=TwoWay}"
        Visibility="Hidden" 
        TextFormatting="0.######"/>
    </s:SciChartSurface.XAxis>

    <s:SciChartSurface.YAxis>
        <s:NumericAxis AxisAlignment="Left"
        DrawMajorGridLines="False"
        DrawMinorGridLines="False"
        DrawMajorBands="False"
        Visibility="Visible">
            <s:NumericAxis.GrowBy>
                <s:DoubleRange Min="0.1" Max="0.1" />
            </s:NumericAxis.GrowBy>
        </s:NumericAxis>

    </s:SciChartSurface.YAxis>

    <s:SciChartSurface.ChartModifier>
        <s:ModifierGroup>
            <s:ZoomExtentsModifier XyDirection="YDirection"/>

            <s:ZoomPanModifier ExecuteOn="MouseMiddleButton" XyDirection="XYDirection" ClipModeX="ClipAtExtents" />

            <local:ExtendedMouseWheelZoomModifier />

            <s:RubberBandXyZoomModifier IsEnabled="True"
                IsXAxisOnly="False"
                ReceiveHandledEvents="True" />
            <s:LegendModifier ShowLegend="True" Orientation="Vertical" Margin="10"
                GetLegendDataFor="AllSeries"
                ShowVisibilityCheckboxes="False" 
                HorizontalAlignment="Right"
                LegendPlacement="Inside"
                Background="White"
                />

            <local:ExtendedSeriesSelectionModifier SelectionChanged="SeriesSelectionModifier_OnSelectionChanged">
                <local:ExtendedSeriesSelectionModifier.SelectedSeriesStyle>
                    <Style TargetType="s:FastLineRenderableSeriesForMvvm">
                        <Setter Property="StrokeDashArray" Value="10,5"/>
                    </Style>
                </local:ExtendedSeriesSelectionModifier.SelectedSeriesStyle>
            </local:ExtendedSeriesSelectionModifier>


            <!--<s:CursorModifier x:Name="cursorModifier" IsEnabled="True" />
        <s:RolloverModifier x:Name="rolloverModifier" IsEnabled="True"/>-->
        </s:ModifierGroup>
    </s:SciChartSurface.ChartModifier>
</s:SciChartSurface>
0 votes
7k views

Hi,

I am developing an MVVM WPF application and need to access the SelectedPointMarkers property of DataPointSelectionModifier from the ViewModel.

From looking at the DataPointSelectionModifier documentation (https://www.scichart.com/documentation/win/current/webframe.html#DataPoint%20Selection.html) I can see how you can get the X and Y coordinate values of a selected point in a view, by binding the PointMarkersSelectionModifier to a listbox.

However this doesn’t really help me, I need to get the coordinates of the SelectedPointMarker into a property inside the ViewModel that can be accessed, rather than just binding to a listbox in the view itself.

I’ve also looked at this similar post: (https://www.scichart.com/questions/wpf/i-want-to-bind-selectedpointmarkers-of-datapointselectionmodifier), but I had no luck getting Kenishis solution to work in my case.

How can i do this?

Thanks.

0 votes
0 answers
8k views

Hello again!
I’m working with new scichart version (5th august). In view XAML file I have this code snippet:

visuals:SciChartSurface Annotations="{Binding AnnotationCollection}"  SeriesSource="{Binding GraphicsCollection}" XAxis="{Binding XAxis, Mode=TwoWay}" YAxes="{Binding YAxisCollection}"  >

When I try to run the application, I get this NullReferenceException:

   в A. .Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
   в System.Windows.Data.BindingExpression.TransferValue(Object newValue, Boolean isASubPropertyChange)
   в System.Windows.Data.BindingExpression.Activate(Object item)
   в System.Windows.Data.BindingExpression.AttachToContext(AttachAttempt attempt)
   в System.Windows.Data.BindingExpression.AttachOverride(DependencyObject target, DependencyProperty dp)
   в System.Windows.Data.BindingExpressionBase.OnAttach(DependencyObject d, DependencyProperty dp)
   в System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
   в System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
   в System.Windows.Data.BindingOperations.SetBinding(DependencyObject target, DependencyProperty dp, BindingBase binding)
   в System.Windows.FrameworkElement.SetBinding(DependencyProperty dp, BindingBase binding)
   в Abt.Controls.SciChart.Visuals.Annotations.LineAnnotationWithLabelsBase.VB()
   в Abt.Controls.SciChart.Visuals.Annotations.LineAnnotationWithLabelsBase.TB()
   в Abt.Controls.SciChart.Visuals.Annotations.LineAnnotationWithLabelsBase.OnXAxesCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
   в Abt.Controls.SciChart.Visuals.Annotations.AnnotationBase.Abt.Controls.SciChart.Visuals.Annotations.IAnnotation.OnXAxesCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
   в Abt.Controls.SciChart.Visuals.Annotations.AnnotationCollection.OnXAxesCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
   в Abt.Controls.SciChart.Visuals.SciChartSurface.OnXAxesCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
   в System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e)

But if I change my xaml file this way:

visuals:SciChartSurface SeriesSource="{Binding GraphicsCollection}" XAxis="{Binding XAxis, Mode=TwoWay}" YAxes="{Binding YAxisCollection}" 
Annotations="{Binding AnnotationCollection}"   >

there won’t be any exceptions. I’ve attached project with exception below.

P.S. in the previuous version it works fine.

  • Egor asked 9 years ago
0 votes
9k views

Hello!

I am trying to programmatically set a range for HeatmapColorPalette and attached HeatmapColorMap to min and max of my data.

Binding HeatmapColorPalette.Maximum to a property in my View Model works well. However, when I add HeatmapColorMap everything breaks, the heat map no longer responds to changes in View Model.

What am I doing wrong?

Here is my View:

<Window x:Class="SciChartHeatMap.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:SciChartHeatMap"
    xmlns:s="http://schemas.abtsoftware.co.uk/scichart"
    d:DataContext="{d:DesignInstance Type=local:HeatMapViewModel, IsDesignTimeCreatable=True}"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid>
    <Grid.Resources>
        <s:GradientStopsToLinearGradientBrushConverter x:Key="ColorsToLinearGradientBrushConverter"/>
    </Grid.Resources>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <s:SciChartSurface Grid.Row="0" Grid.RowSpan="2">
        <s:SciChartSurface.RenderableSeries>
        <s:FastUniformHeatmapRenderableSeries x:Name="HeatMapSeries" DataSeries="{Binding Data}" Opacity="0.9">
            <s:FastUniformHeatmapRenderableSeries.ColorMap>
                <s:HeatmapColorPalette Maximum="{Binding ColorMaximum}">
                    <s:HeatmapColorPalette.GradientStops>
                        <GradientStop Offset="0" Color="DarkBlue"/>
                        <GradientStop Offset="0.2" Color="CornflowerBlue"/>
                        <GradientStop Offset="0.4" Color="DarkGreen"/>
                        <GradientStop Offset="0.6" Color="Chartreuse"/>
                        <GradientStop Offset="0.8" Color="Yellow"/>
                        <GradientStop Offset="1" Color="Red"/>
                    </s:HeatmapColorPalette.GradientStops>
                </s:HeatmapColorPalette>
            </s:FastUniformHeatmapRenderableSeries.ColorMap>
        </s:FastUniformHeatmapRenderableSeries>
        </s:SciChartSurface.RenderableSeries>
        <s:SciChartSurface.XAxis>
            <s:NumericAxis 
                FlipCoordinates="False" 
                ScientificNotation="None" 
                AutoTicks="False"
                MajorDelta="1"
                MinorDelta="0.5"
                AxisAlignment="Top"/>
        </s:SciChartSurface.XAxis>
        <s:SciChartSurface.YAxis>
            <s:NumericAxis 
                FlipCoordinates="True" 
                ScientificNotation="None"
                AxisAlignment="Left"/>
        </s:SciChartSurface.YAxis>
    </s:SciChartSurface>

    <!-- Enabling this will break the program
    <s:HeatmapColorMap
        Grid.Column="1"
        Grid.Row="0"
        Grid.RowSpan="2"
        Margin="5,0,5,0"
        HorizontalAlignment="Right"
        VerticalAlignment="Stretch"
        DataContext="{Binding Source={x:Reference Name=HeatMapSeries}, Mode=OneWay}"
        ColorMap="{Binding ColorMap.GradientStops, Converter={StaticResource ColorsToLinearGradientBrushConverter}}"
        Maximum="{Binding ColorMap.Maximum}"
        Orientation="Vertical">
    </s:HeatmapColorMap>
    -->

    <Label 
        Grid.Row="0" 
        Grid.Column="2" 
        Content="{Binding ColorMaximum}" 
        Width="50" 
        HorizontalContentAlignment="Center"/>
    <Slider 
        Grid.Column="2" 
        Grid.Row="1" 
        Orientation="Vertical" 
        Minimum="0" 
        Maximum="10" 
        HorizontalAlignment="Center"
        Value="{Binding ColorMaximum}"/>
</Grid>

The idea in this small example is for slider to control both HeatmapColorPalette.Maximum and s:HeatmapColorMap.Maximum

The code in my View Model is pretty simple:

private double mColorMax;

public double ColorMaximum
    {
        get => mColorMax;

        set
        {
            mColorMax = value;
            OnPropertyChanged();
        }
    }

My View Model implements INotifyPropertyChanged

I will appreciate any suggestions.

Thank you in advance!

0 votes
10k views

I’m trying to implement custom annotations using the MVVM pattern. I’ve been using your tutorial as an example (https://www.scichart.com/databinding-annotations-with-mvvm/). Everything works as expected if I manually load some example data to the annotations collection. When I actually try to load the data from our database using async method, the annotations are no longer drawn.

Is this by design or am I doing something wrong? Do you have any suggestions how to load annotations when using async code and MVVM patterns? I haven’t had any problems loading the actual time series on the chart using the same pattern.

I also tried binding the SciChartSurface’s Annotations property to AnnotationCollection and then calling ChartAnnotations.ParentSurface.InvalidateElement(), but the issue still persists.

You can easily reproduce this behavior by adding an async call to the examples’s source code:

private async Task Initialize()
{
    var ds0 = new XyDataSeries<double, double>();
    var someData = new RandomWalkGenerator().GetRandomWalkSeries(200); // RandomWalkGenerator is found in the examples source code

    ds0.Append(someData.XData, someData.YData);

    _chartSeries = new ObservableCollection<IChartSeriesViewModel>();
    _chartSeries.Add(new ChartSeriesViewModel(ds0, new FastLineRenderableSeries()));

    // Now create the labels
    _chartLabels = new List<LabelViewModel>
                       {
                           new LabelViewModel(5, -2.5, "Label0", "Label0 Tooltip!"),
                           new LabelViewModel(20, -2, "Label1", "Label1 Tooltip!"),
                           new LabelViewModel(35, 3, "Label2", "Label2 Tooltip!"),
                           new LabelViewModel(50, 1.5, "Label3", "Label3 Tooltip!"),
                       };

    await Test();

    _chartLabels.Add(new LabelViewModel(65, -0.5, "AFTER ASYNC", "Label4 Tooltip!"));
}

private async Task Test()
{
    await Task.Delay(5000);
}
  • Juho asked 7 years ago
  • last active 7 years ago
0 votes
3k views

Hi,

I’m trying to evaluate the reality of creating multiple realtime charts and I’m hitting a huge performance brick wall.

My application will have high speed streamed data coming in over ethernet. Currently I’m simulating this with a thread timer that updates 100 data objects at 60Hz. Screen data and chart updates I’ve got throttled to 30Hz but it’s still grinding my charts are still struggling. If I move the mouse pointer the charts freeze entirely until the mouse is still.

I want the end user to be able to choose any data object and chart it however they want. Adding charts and adding plots to charts etc. To enable this I’ve created a chart template as a user control and at runtime the charts are added to a panel on a tab control. Event one chart on one tab chugs though. Move the mouse over it and it locks up.

I have a single overview chart with a scrollbar over the top on the parent control. I need this to control the cursor (vertical line) and shared X visible range. Live data is Fifo limited to a 10 second range. All this works, just painfully slowly.

SharedXVisible range is MVVM bound. Renderable series is LineRenderableSeriesViewModel and data is pushed at 30Hz from a Data provider as per this tutorial:
https://www.scichart.com/documentation/win/current/Tutorial%2006b%20-%20Adding%20Realtime%20Updates%20with%20MVVM.html

CPU usage is sub 20%. Max frame rate is 30fps. Render priority doesn’t seem to make much difference, though “immediate” will lock up the whole app. I’m no expert at performance profiling but I’m not getting any clues from ReShaper dotTrace so far.

I tried creating a version that hand almost no binding and used codebehind to update the data. It didn’t seem to help. I’d rather not do this though as I have a lot of things working that I like such as vertical slice, annotations, templates etc.

I’ve got a list of all the live data on the right of the screen and it all updates rapidly, even while the mouse is moving and the charts are frozen.

I’m also using some Syncfusion controls and theming, if it matters.

I must be missing something obvious surely.

<!--  Define Chart  -->
        <s:SciChartSurface x:Name="chart" Grid.Row="0" Grid.Column="0"
                           Background="Black"
                           RenderPriority="low"
                           MaxFrameRate="30"
                           RenderableSeries="{s:SeriesBinding RenderableSeriesCollection}"
                           >

            <!--  Define X and Y Axis  -->
            <s:SciChartSurface.YAxis>
                <s:NumericAxis AutoRange="{Binding AxisYRangeMode}" 
                               DrawMajorBands="False" 
                               DrawMinorGridLines="false" 
                               DrawMajorGridLines="True" 
                               DrawMajorTicks="False" 
                               DrawMinorTicks="False" 
                               VisibleRange="{Binding AxisYVisibleRange}" />
            </s:SciChartSurface.YAxis>

            <s:SciChartSurface.XAxis>
                <s:NumericAxis AutoRange="{Binding AxisXRangeMode}" 
                               BorderBrush="{StaticResource BorderBrushGray}" 
                               BorderThickness="1" 
                               DrawMajorBands="False" 
                               DrawMinorGridLines="False" 
                               DrawMajorGridLines="True" 
                               DrawMajorTicks="False" 
                               DrawMinorTicks="False" 
                               TextFormatting="0" 
                               VisibleRange="{Binding SharedXVisibleRange, Mode=TwoWay}" 
                               s:VerticalSliceModifier.AxisLabelContainerStyle="{x:Null}"/>
            </s:SciChartSurface.XAxis>

            <!--  Modifiers  -->
            <s:SciChartSurface.ChartModifier>
                <s:ModifierGroup>
                    <s:RubberBandXyZoomModifier 
                        IsXAxisOnly="True" 
                        ZoomExtentsY="True" 
                        IsAnimated="True" 
                        RubberBandFill="#20FFFFFF" 
                        RubberBandStroke="GreenYellow" 
                        RubberBandStrokeDashArray="2 2">
                    </s:RubberBandXyZoomModifier>

                    <s:ZoomExtentsModifier IsAnimated="True"/>

                    <s:MouseWheelZoomModifier IsEnabled="True"/>

                    <s:XAxisDragModifier IsEnabled="True" DragMode="Pan"/>

                    <s:LegendModifier x:Name="legendModifier"
                                      Background="Transparent" 
                                      Margin="10" 
                                      GetLegendDataFor="AllSeries" 
                                      LegendItemTemplate="{StaticResource CustomLegendTemplate}" 
                                      ShowLegend="True" ShowVisibilityCheckboxes="True"/>

                    <s:VerticalSliceModifier Name="sliceModifier">

                    <s:VerticalSliceModifier.VerticalLines>
                            <s:VerticalLineAnnotation Style="{StaticResource sliceStyle}" 
                                                      X1="{Binding SlicePosition, Mode=TwoWay}"/>
                        </s:VerticalSliceModifier.VerticalLines>
                    </s:VerticalSliceModifier>

                </s:ModifierGroup>
            </s:SciChartSurface.ChartModifier>
        </s:SciChartSurface>

Thanks in advance,
Declan.

PS. I’m trying to attach a screenshot but it keeps saying “Forbidden”.

0 votes
11k views

Hi,

Was hoping you could point me in the right direction. I’m trying to create horizontal line annotations on demand using MVVM but have become stuck. I’ve have them working in MVVM when the chart loads but not when a button is clicked although I have achieved this using code behind.

I’ve tried using an observable collection of AnnotationCollection type but am struggling to add the horizontal lines annotations to it as they are of a different type.

Any pointers in the right direction would be much appreciated!

Thanks,
Tim

Example of MVVM

TradeAnnotations = CreateHorizontalAnnotations();

private AnnotationCollection _annotations;

    public AnnotationCollection TradeAnnotations
    {
        get { return _annotations; }
        set
        {
            _annotations = value;
            OnPropertyChanged("TradeAnnotations");
        }
    }

    private static AnnotationCollection CreateHorizontalAnnotations()
    {
        //var annotations = new AnnotationCollection();

        var annotations = new AnnotationCollection();

        Color strokeColor = (Color)ColorConverter.ConvertFromString("#008B45");
        Brush strokeBrush = new SolidColorBrush(strokeColor);

        HorizontalLineAnnotation annotation = new HorizontalLineAnnotation();

        annotation.ShowLabel = true;
        annotation.LabelPlacement = LabelPlacement.Axis;
        annotation.HorizontalAlignment = HorizontalAlignment.Stretch;
        annotation.IsEditable = true;
        annotation.SnapsToDevicePixels = true;
        annotation.Stroke = strokeBrush;

        annotation.X1 = DateTime.Now;
        annotation.Y1 = 129;

        annotations.Add(annotation);

        return annotations;          
    }

Example of code behind

        private void CreateHorizontalAnnotations(object sender, System.Windows.RoutedEventArgs e)
    {
        //var annotations = new AnnotationCollection();

        var annotationCollection = new AnnotationCollection();

        Color strokeColor = (Color)ColorConverter.ConvertFromString("#008B45");
        Brush strokeBrush = new SolidColorBrush(strokeColor);

        HorizontalLineAnnotation annotation = new HorizontalLineAnnotation();

        annotation.ShowLabel = true;
        annotation.LabelPlacement = LabelPlacement.Axis;
        annotation.HorizontalAlignment = HorizontalAlignment.Stretch;
        annotation.IsEditable = true;
        annotation.SnapsToDevicePixels = true;
        annotation.Stroke = strokeBrush;

        annotation.X1 = DateTime.Now;
        annotation.Y1 = 129;

        this.priceChart.Annotations.Add(annotation);
    }
0 votes
0 answers
6k views

I have a TabControl that contains a dynamic number of chart panes via an ItemsControl. Inside the ItemsControl’s ItemsTemplate is a single ScichartSurface with bindings to the RenderableSeries, XAxis, YAxes, and VerticalChartGroup.

The xaml looks something like this:

<s:SciChartSurface name="Chart" RenderableSeries="{Binding rSeries}" XAxis={Binding xAxis} YAxes={Binding yAxes} s:SciChartGroup.VerticalChartGroup="{Binding vGroup}">

Within the surface, I have a ModifierGroup that contains (in order) a RubberbandXyZoomModifier (XAxisOnly), MouseWheelZoomModifier, ZoomPanModifier, ZoomExtentsModifier, and a custom mod call TimeSegmentSelectionModifier. All of these modifiers have their ReceiveHandledEvents property set to True, they are all under the same MouseEventGroup, and they all seem to work fine under normal circumstances.

Note: The Rubberband and TimeSegment modifiers are inversely set to Enabled. Meaning, only one of them functions at a time.

My issue is primarily with the RubberBand Mod:

Let’s say I have 5 chart panes being displayed and I want to zoom in; If I click and drag within the 3rd chart, every chart zooms correctly.
If I click withing the 3rd chart, drag the mouse outside of that chart (anywhere else on my screen) and let go, then only charts 1, 2, and 3 are zoomed correctly. Charts 4 and 5 won’t budge and act as if I had merely zoomed to extents.

This happens with any number of chart panes and the issue occurs on whatever pane I happened to be zooming in on.

I’ve been troubleshooting this issue for a few days now and I don’t know where else to look.
Any help is greatly appreciated.

0 votes
8k views

Hello,

I have created some ChartModifiers in a ModifierGroup in my ViewModel class (using Caliburn.Micro as MVVM framework, not code behind) and bound the group to my SciChartSurface in xaml. Now I want to apply some styles to my modfiers in xaml. Just creating styles with the specific target types don’t work so how do I do this?

  • Roland D asked 5 years ago
  • last active 5 years ago
0 votes
8k views

I am trying to bind from my ViewModel to the DataSeries of a ScatterRenderableSeries3D, but no data is showing.

I am binding in this way:

My ViewModel has a property of type ObservableCollection<XyzDataSeries3D<DateTime, double, int>>. I can populate ChartItems, and see the data in it. The property is being notified of change as expected.

If I populate the DataSeries directly from code behind, it works, but not when being bound.

What am I doing wrong?

0 votes
7k views

Is there a way to apply functionalities on signals as in average, slope, etc. ?

Thank you
Anders

0 votes
0 answers
9k views

I try to add data series and have them rendered on a chart surface. The surface and entire chart library is wrapped in an mvvm-based api. The sci chart control and wrapping library are rendered on a document panel. I add new data series via the viewmodel and here is where I have some unexpected behavior:

a) When being on a different document panel, meaning the chart control is NOT visible, and when I add a new data series via view model and then view the document panel that hosts the sci chart control, no chart series are rendered on the chart but I do see the correct legend data (such as chart series name, color, stroke thickness). Please see below screen shot “Capture1.jpg” .

b) When I make the sci chart control visible by viewing the document panel that hosts the sci chart control and then via a button and command add the very same data series via my chart control’s view model the charts are correctly rendered. Please see “Capture2.jpg”.

My question is why is that the case? I basically expose a method in my chart library view model that lets me add data and if I invoke that methods while being on a document panel that does not host the chart control the added data series is not rendered on the chart. But strangely the correct chart legend data are displayed and also the chart control itself is correctly rendered. No problems when the hosting document panel is active and the very same method is invoked.

Basically what I currently observe is that the data series are not rendered at all as long as the chart control is not “in view” or the hosting document panel is not selected. I am sure programmatically all references and bindings are correct.

I have spend many hours debugging this issue and do not seem to find an answer. Any pointers?

Thanks a lot,
Matt

Edit:

Here is how I bind the content control to the view model of my sci chart charting library (user control)

<ContentControl Grid.Row="1" Content="{Binding ChartControl, Mode=OneWay}" />

…and the view model is instantiated in the hosting view model constructor:

public MainWindowViewModel()
    {
       ChartControl = new SciChartControlViewModel();

        ExitApplicationCommand = new RelayCommand(OnExitApplicationCommand);
        LoadDataSeriesFromFilesCommand = new RelayCommand(OnLoadDataSeriesFromFilesCommand);
        RefreshDataSeriesFromFilesCommand = new RelayCommand(OnRefreshDataSeriesFromFilesCommand);


        Test();

    }

…Test() performs the following action:

private void Test()
    {
        var quotes = new List<Quote>();
        List<DateTime> timeStamps = new List<DateTime>();
        List<double> values = new List<double>();
        List<SciChartAnnotation> annotations = new List<SciChartAnnotation>();
        Random rand = new Random((int)DateTime.Now.Ticks);
        DateTime currentDt = DateTime.Now;
        double currentValue = 0;

        for (int index = 0; index <= 50000; index++)
        {
            var randomValue = rand.NextDouble();
            currentDt = currentDt + TimeSpan.FromSeconds(randomValue);
            currentValue = currentValue + randomValue - 0.5;

            if (index % 1000 == 0)
            {
                var buySell = rand.NextDouble() > 0.5 ? SciChartAnnotationDirection.Buy : SciChartAnnotationDirection.Sell;
                annotations.Add(new SciChartAnnotation(buySell, currentDt, currentValue, "Index:" + index));
            }

            timeStamps.Add(currentDt);
            values.Add(currentValue);

            quotes.Add(new Quote(){DataProviderId = "Provider1", SymbolId = "Symbol1", QuoteType = QuoteType.BidAsk, CompressionType = TimeCompressionType.NoCompression, CompressionUnits = 0, TimeStamp = currentDt, Bid = currentValue, Ask= currentValue + 0.05, });

        }

        ChartControl.AddDataSet("Pane1", "0.00000", quotes, annotations);
        //ChartControl.AddDataSet("MattSeries", ChartType.Scatter, 1, "0.00000", timeStamps, values);

    }

…it basically tries to render chart series and annotations.

Strangely, as mentioned before, the series legends render correctly and the annotations also all render correctly but the chart series do not! Could this be a bug? Please refer to the image “Capture3” for a screenshot.

  • bbmat asked 9 years ago
  • last active 9 years ago
0 votes
11k views

Hello support team.

I have a question about the resampling modes and their behavior.
I have a LineRenderableSeries with the resampling mode.mid. Therefore, depending on the zoom level and available pixels of the display screen, the information of the min and max values are lost. I had the idea to create a second LineRenderableSeries with the Opacity 0.5 and the ResamplingMode.Min Max. Thus I have behind the main line with the resampling mode.mid a “cloud” with the MinMax info. This allows the user to see this information as well. However, I would deactivate this cloud if it is not necessary due to the zoom level and the pixels.
How can I request this from SciChartControl? Or does it make more sense to use a different functionality?
I use the Mvvm classes LineRenderableSeriesViewModel, and XyDataSeries.

Thank you very much!

0 votes
8k views

I’m trying to set the visible range property of a CategoryDateTimeAxis through MVVM. I’m following the general instructions detailed here for converting between pixel & data coordinates on the axis:

https://www.scichart.com/questions/question/categorydatetimeaxis-in-mvvm#sabai-inline-nav

I have the following code in my viewmodel:

XAxis.OnBeginRenderPass();
var calc = XAxis.GetCurrentCoordinateCalculator();
var coordCalc = calc as ICategoryCoordinateCalculator;

XAxis is a CategoryDateTimeAxis injected from the view. I call OnBeginRenderpass as I saw in another forum post that this will ensure that the CoordinateCalculator is initialized.

calc shows in the debugger as:

  • calc {A.} Abt.Controls.SciChart.Numerics.CoordinateCalculators.ICoordinateCalculator {A.}

The coordCalc variable ends up assigned to NULL, as the ICoordinateCalculator< double > cannot be cast to the interface.

How do I accomplish the above?

Thanks, Asher

  • ashernew asked 8 years ago
  • last active 8 years ago
0 votes
9k views

Hello!

I am getting started with SciChart and attempting to use it for a project I’m working on.

I am attempting to make a 3D scatter plot whose data is populated through a ViewModel.

Below is a my xaml:

 <UserControl x:Class="CustomWindow.Pages.Results_Page.Common_Tests.Positional6DOFErrorTest"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:enum="clr-namespace:MultiMet.Interfaces.Common;assembly=MultiMet.Interfaces"
             xmlns:xcdg="http://schemas.xceed.com/wpf/xaml/datagrid"
             xmlns:s3D="http://schemas.abtsoftware.co.uk/scichart3D"
             mc:Ignorable="d" 
             d:DesignHeight="360" d:DesignWidth="712">

    <Grid Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <!-- Some other stuff I'm doing on the page -->

        <s3D:SciChart3DSurface Grid.Column="1" ShowLicensingWarnings="True"
                        IsFpsCounterVisible="False"
                         IsAxisCubeVisible="True"
                         IsXyzGizmoVisible="False"
                         CoordinateSystem="RightHanded"
                               Background="White" RenderableSeries="{s3D:SeriesBinding RenderableSeries3DViewModels}">
            <!-- Create XAxis -->
            <s3D:SciChart3DSurface.XAxis>
                <s3D:NumericAxis3D TickTextBrush="Black" AxisTitle="X (mm)" DrawMajorBands="True" DrawMajorGridLines="True"
                        DrawMinorGridLines="True"
                        DrawMajorTicks="True"
                        DrawMinorTicks="True"
                        AxisBandsFill="Transparent"
                        FontSize="10"
                        TickLabelAlignment="Camera"
                                   GrowBy="0.1, 0.1"/>
            </s3D:SciChart3DSurface.XAxis>
            <!-- Create YAxis -->
            <s3D:SciChart3DSurface.YAxis>
                <s3D:NumericAxis3D AxisTitle="Z (mm)"
                        AxisBandsFill="Transparent"
                        TickTextBrush="Black"
                        FontSize="10"
                        TickLabelAlignment="Camera"
                                   GrowBy="0.1, 0.1"/>
            </s3D:SciChart3DSurface.YAxis>
            <!-- Create ZAxis -->
            <s3D:SciChart3DSurface.ZAxis>
                <s3D:NumericAxis3D AxisTitle="Y (mm)"
                        AxisBandsFill="Transparent"
                        TickTextBrush="Black"
                        FontSize="10"
                        TickLabelAlignment="Camera"
                                   GrowBy="0.1, 0.1"/>
            </s3D:SciChart3DSurface.ZAxis>

            <!-- Create Interactivity Modifiers for rotating camera -->
            <s3D:SciChart3DSurface.ChartModifier>
                <s3D:ModifierGroup3D>
                    <s3D:OrbitModifier3D ExecuteOn="MouseLeftButton" ExecuteWhen="None"/>
                    <s3D:MouseWheelZoomModifier3D MouseWheelSensitivity="90" />
                    <s3D:FreeLookModifier3D ExecuteOn="MouseRightButton"/>
                    <s3D:TooltipModifier3D IsEnabled="True" SourceMode="AllSeries" ShowTooltipOn="MouseOver"/>
                </s3D:ModifierGroup3D>
            </s3D:SciChart3DSurface.ChartModifier>
        </s3D:SciChart3DSurface>
    </Grid>
</UserControl>

And below I declare and define my scatter plot in the viewmodel (the scatterSeries is an XyzDataSeries3D set somewhere else) :

    PositionalErrorTestModel.RenderSeries3DViewModels = new ObservableCollection<IRenderableSeries3DViewModel>();
PositionalErrorTestModel.RenderSeries3DViewModels.Add(new ScatterRenderableSeries3DViewModel
            {
                PointMarker = new SpherePointMarker3D { Fill = System.Windows.Media.Color.FromRgb(0x78, 0xC3, 0), Size = 5, Opacity = 1 },
                DataSeries = scatterSeries
            });

The chart appears, but the data does not. Is there something I’m missing? Do I need to explicitly call an update to the chart? Because the page the chart is on and the chart does get loaded before the data is populated.

Please let me know if you need to know anymore information.

Thanks for any help you can provide!

0 votes
0 answers
6k views

Hello Andrew & Co.

I need some guidance in an attempt to add some required functionality to my SciChart application.

A requirement has been brought to my attention where a user wants to do a graph over lay from a different time snap shot . This is useful for comparison reasons, where the engineer wants to compare a previous successful execution of a process with a current running one.

  • One part of the solution is to save the dataseries info from a finite
    time period in the past.
  • Second part is that the overlaid trend (dataseries) need to be time
    XAxis independent but YAxis relative.

I am looking at two different scenarios let me see what you guys think:

  1. Overlaid historic static trend on existing chart surface
  2. Historic static trend in a new chart surface (smaller format) on the
    bottom of the current chart surface being displayed

How should I best approach such an implementation ? The application is using the MVVM pattern. I have adhered to the pattern pretty religiously so far

Hopefully that makes sense to describe what I am trying to accomplish.
Appreciate your support and expert guidance in this matter

Thanks
Anders

0 votes
0 answers
8k views

I noticed that there are problems when I try to add data series, create renderable series, or annotations while the view that hosts the scichartgroup and/or scichartsurface(s) is/are not yet initialized/rendered. Could this be a bug? After all it should not matter when the view is rendered; when it is rendered its elements bind to the matching properties of its viewmodel, no?

This poses problems for me because I am forced to take the viewmodel-first approach. So, when I create an instance of my viewmodel and then invoke methods in the viewmodel that add data series and render such I am experiencing errors (the rendered series is not displayed on the chart, though annotations strangely are).

I identified the problem to be 2-fold, one is that I have to create renderable series on the UI thread (solved that, no issue) but my other big problem is that the view is actually not instantiated/rendered unless the view is in focus/visible which is not the case during runtime when data series are added via viewmodel.

How can I solve this problem?

  • bbmat asked 9 years ago
  • last active 9 years ago
0 votes
8k views

Using MVVM, I have an AnnotationCollection databound to the SciChartSurface.Annotations. Individual LineAnnotations are added to the collection as the application code runs.

If annotations are added while the chart is displayed, they are all drawn correctly.

However, if the chart page is reloaded (say, the user navigates to a different page and then returns to the chart page), the annotations do not always redraw. If the annotations have AnnotationCanvas set to default (AnnotationCanvas.AboveChart, I believe) they redraw correctly about 50% of the time. If the annotations’ AnnotationCanvas is set to AnnotationCanvas.XAxis, they never redraw.

All the annotations still exist in the ObservableCollection in all these cases, so they shouldn’t need to be re-created.

Is this a bug in SciChart or is there something I may be doing wrong with the annotations?
(There is only one X-Axis so no axisID is necessary.)

LineAnnotation lAnno = new LineAnnotation();
lAnno.CoordinateMode = AnnotationCoordinateMode.RelativeY;
lAnno.Y1 = 0.0;
lAnno.X1 = DataPoints;
lAnno.Y2 = 1.0;
lAnno.X2 = DataPoints;
lAnno.YAxisId = "Counts";
lAnno.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 255, 255));
lAnno.Stroke = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(96, 255, 0, 0));
lAnno.StrokeThickness = 2;
lAnno.AnnotationCanvas = AnnotationCanvas.XAxis;

Markers.Add(lAnno);
0 votes
7k views

Hi,
I’m experimenting with the LegendModifier and want to control which RenderableSeries are shown via the “LegendItemTemplate” approach. The idea is to add a specific tagging class to the RenderableSeries.DataSeries.Tag and use the content inside the LegendItemTemplate which I define in the Window.Resouces.

The tagging Class:

public class DataSeriesTag
{
    public string LegendText { get; set; }
    public bool ShowLegend { get; set; }
}

The LegendItemTemplate:
<Window.Resources>


<Grid.ColumnDefinitions>

</Grid.ColumnDefinitions>

            <!--<CheckBox Width="16" Margin="5,0,0,0"
                HorizontalAlignment="Left"
                VerticalAlignment="Center"
                IsChecked="{Binding RenderableSeries.IsVisible, Mode=TwoWay}"
                Visibility="{Binding RenderableSeries.DataSeries.Tag.ShowLegend, Converter={dxmvvm:BooleanToVisibilityConverter}}" />-->

            <s:PointMarker Grid.Column="1" Margin="5,0,0,0" Width="40" Height="10" VerticalAlignment="Center" HorizontalAlignment="Center"
              DataContext="{Binding RenderableSeries}"
              DeferredContent="{Binding LegendMarkerTemplate}"
              Visibility="{Binding ShowSeriesMarkers, RelativeSource={RelativeSource AncestorType=s:SciChartLegend}, Converter={dxmvvm:BooleanToVisibilityConverter}}" />

            <TextBlock Margin="5,0,5,0"
     Grid.Column="2"
     HorizontalAlignment="Left"
     Text="{Binding RenderableSeries.DataSeries.Tag.LegendText}" />

        </Grid>
    </DataTemplate>
</Window.Resources>

As long as I declare the SciChartSurface.ChartModifier in XAML, it works perfect.
The proplem raises when I bind the ModifierGroup to a ViewModel Property and try to build the LegendModifier there. How can I assign the LegendItemTemplate in the ViewModel?:

legendModifier = new LegendModifier(){
            ShowLegend = true,
            ShowVisibilityCheckboxes = false,
            LegendItemTemplate = ??????
        };
        TheModifiers.ChildModifiers.Add(legendModifier);

Kind regards
Martin

0 votes
8k views

Hi,

CompositeAnnotation works perfectly and easy to use, but I need it in MVVM. CompositeAnnotationViewModel looks the same, but it is not visible. This is my code:

AnnotationViewModels.Add(new CompositeAnnotationViewModel()
{
    Annotations = new ObservableCollection<IAnnotationViewModel>()
    {
        new VerticalLineAnnotationViewModel
        {
            VerticalAlignment = VerticalAlignment.Stretch,
            Stroke = Colors.Blue,
            StrokeThickness = 2,
            IsEditable = true,
            StrokeDashArray = new DoubleCollection() { 2, 2 },
            CoordinateMode = AnnotationCoordinateMode.Relative,
            X1 = 0
        },
        new VerticalLineAnnotationViewModel
        {
            VerticalAlignment = VerticalAlignment.Stretch,
            Stroke = Colors.Blue,
            StrokeThickness = 2,
            IsEditable = true,
            StrokeDashArray = new DoubleCollection() { 2, 2 },
            CoordinateMode = AnnotationCoordinateMode.Relative,
            X1 = 1
        }
    },
    IsEditable = true,
    X1 = 3,
    X2 = 5
});

What is my mistake?

0 votes
7k views

Hi,

Could you provide some Mvvm examples that include:

1) Mvvm bubble chart where the Fill color is defined on the series view model
2) custom tooltips per point where the tooltip string is defined on the point view model

I have both of these kind of working using a workaround based on the obsolete SciChartSurface.SeriesSource property, but now I’m trying to migrate to SciChartSurface.RenderableSeries and the proper Mvvm API and I cannot find all the elements I need.

Cheers
Felix

  • F W asked 8 years ago
  • last active 8 years ago
0 votes
0 answers
6k views

I’ve been moving a project over to using MVVM, but I’ve found the IsStaticAxis option I was using in the NumericAxis doesn’t exist in the NumericAxisViewModel. Is it not possible to make the axis static with the View Models?

0 votes
8k views

Hi! I have problems with visible range managing of a polar plot

The code in xaml:

<s:SciChartSurface graphModule:PlotLengthHelper.PlotLength="{Binding PlotLength, Mode=OneWayToSource,   UpdateSourceTrigger=PropertyChanged}" 
                       x:Name="ChartSurface"
                       SizeChanged="ChartSurface_OnSizeChanged"
                        ChartTitle="{Binding ChartTitle}"
                       s:ThemeManager.Theme="BrightSpark"
                        Annotations="{s:AnnotationsBinding Annotations}"
                       RenderableSeries="{s:SeriesBinding Series}"
                       XAxes="{s:AxesBinding XAxes}"
                       YAxes="{s:AxesBinding YAxes}"

First example. The code of the axis:

    var yAxis = new PolarYAxisViewModel {AutoRange = AutoRange.Never};
    YAxes.Add(yAxis);

Changing the VisibleRange of the axis has no any effect on the visible range of the graph. It sets automatically in the very first time and remains the same.

Second example.

    var yAxis = new PolarYAxisViewModel {AutoRange = AutoRange.Always};
    YAxes.Add(yAxis);

Changing the data (using line series) again has no any effect on the visible range of the graph. Again, it sets automatically in the very first time and remains the same.

Any suggestion on how to fix it? Especially the first case is required. Thanks.

0 votes
3k views

Hello.
Thanks for previous answer but I can’t check how it work because of new problem. I develop WPF application and try to use MVVM as architecture pattern. In the Model part of my application I used a loop started in the new thread. In that loop I get some data which received to ViewModel and used as chart data. Looks as usual.
But then I tried to set visible range updated object which bound to axis I get exception ‘System.InvalidOperationException: ‘The calling thread cannot access this object because a different thread owns it.’ in my loop. I know it happens in WPF applications and need to use Dispatcher to solve it. But as I know if you try to use MVVM you not needed to use Dispatcher often because WPF-binding in most cases is thread-safe. That happend in my case? How to solve it?
Parts of my code:

XAML

<Window x:Class="HMI.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:s="http://schemas.abtsoftware.co.uk/scichart"
        xmlns:localVM="clr-namespace:MyCom.HMI.ViewModel"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <localVM:HMIViewModel/>
    </Window.DataContext>
    <Window.Resources>
        <localVM:InverseBooleanConverter x:Key="InverseBooleanConverter"/>
        <localVM:ProcessStateToColorConverter x:Key="ProcessStateToColorConverter"/>
        <localVM:ProcessStateToStartedConverter x:Key="ProcessStateToStartedConverter"/>
        <localVM:ProcessStateToStoppedConverter x:Key="ProcessStateToStoppedConverter"/>
    </Window.Resources>
    <DockPanel>
        <StackPanel DockPanel.Dock="Top" Orientation="Horizontal">
            <StackPanel DockPanel.Dock="Left" Orientation="Vertical" Width="520">
                <Border DockPanel.Dock="Top" Margin="5" Padding="5" BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
                    <StackPanel DockPanel.Dock="left" Orientation="Horizontal" Height="40">
                        <Ellipse Margin="5" Height="20" Width="20" HorizontalAlignment="Left" VerticalAlignment="Center" Stroke="Black" Fill="{Binding ProcessState, Converter={StaticResource ProcessStateToColorConverter}}"/>
                        <Label Content="State" Margin="5" Width="90" HorizontalContentAlignment="Left" VerticalContentAlignment="Center"/>
                    </StackPanel>
                </Border>
                <Border DockPanel.Dock="Top" Margin="5" Padding="5" BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
                    <Grid DockPanel.Dock="Left" Height="300">
                        <s:SciChartSurface ChartTitle="Profil" RenderableSeries="{s:SeriesBinding RenderableSeries}">
                            <s:SciChartSurface.XAxis>
                                <s:NumericAxis AxisTitle="Position, m" VisibleRange="{Binding XVisibleRange, Mode=TwoWay}"/>
                            </s:SciChartSurface.XAxis>
                            <s:SciChartSurface.YAxis>
                                <s:NumericAxis AxisTitle="Size, um" VisibleRange="{Binding YVisibleRange, Mode=TwoWay}"/>
                            </s:SciChartSurface.YAxis>
                        </s:SciChartSurface>
                    </Grid>
                </Border>
            </StackPanel>
...

ViewModel

namespace MyCom.HMI.ViewModel
{
    public class HMIViewModel : BindableBase
    {      
        private readonly HMIModel _model = new();

        public HMIViewModel()
        {
            _renderableSeries = new ObservableCollection<IRenderableSeriesViewModel>();

            ((INotifyCollectionChanged)_model.TestControlData).CollectionChanged += (s, e) =>  { TestControlDataChanged(e); };

            InitCharts();
        }

...

        private ObservableCollection<IRenderableSeriesViewModel> _renderableSeries;
        public ObservableCollection<IRenderableSeriesViewModel> RenderableSeries
        {
            get { return _renderableSeries; }
            set
            {
                SetProperty(ref _renderableSeries, value, nameof(RenderableSeries));
            }
        }

        private IRange _xVisibleRange;
        public IRange XVisibleRange
        {
            get => _xVisibleRange;
            set
            {
                if (_xVisibleRange != value)
                {
                    SetProperty(ref _xVisibleRange, value, nameof(XVisibleRange));
                }
            }
        }

        private IRange _yVisibleRange;
        public IRange YVisibleRange
        {
            get => _yVisibleRange;
            set
            {
                if (_yVisibleRange != value)
                {
                    SetProperty(ref _yVisibleRange, value, nameof(YVisibleRange));
                }
            }
        }

        private XyDataSeries<double, double> _lineDataDiameter1;

...

        private void InitCharts()
        { // TODO
            _lineDataDiameter1 = new XyDataSeries<double, double>()
            { 
                SeriesName = "Diameter1"
            };

            RenderableSeries.Add(new LineRenderableSeriesViewModel()
            {
                StrokeThickness = 2,
                Stroke = Colors.SteelBlue,
                DataSeries = _lineDataDiameter1,
                StyleKey = "LineSeriesStyle"
            });
        }

        private void TestControlDataChanged(NotifyCollectionChangedEventArgs args)
        {
            if (args.Action == NotifyCollectionChangedAction.Add && args.NewItems?.Count > 0)
            {
                var testControlActualState = args.NewItems.Cast<TestControlActualState>();

                List<double> xValues = new();
                List<double> yValuesDiameter1 = new();

                foreach (var item in testControlActualState) 
                {
                    if (item.Diameter1 > 0f)
                    {
                        xValues.Add(item.FiberLength);
                        yValuesDiameter1.Add(item.Diameter1);
                    }
                }

                _lineDataDiameter1.Append(xValues, yValuesDiameter1);

                // TODO
                if (xValues.Count > 0)
                {
                    var cuurMaxValueX = xValues.Max();
                    XVisibleRange.Max = cuurMaxValueX;
                    XVisibleRange.Min = cuurMaxValueX - 7000f > 0 ? cuurMaxValueX - 7000f : 0;
                }

                // TODO
                if (yValuesDiameter1.Count > 0)
                {
                    var cuurMaxValueY = yValuesDiameter1.Max();
                    YVisibleRange.Max = cuurMaxValueY + 50;
                    YVisibleRange.Min = 0;
                }
            }
        }

Model

namespace MyCom.HMI.Model
{
    public class HMIModel : BindableBase, IDisposable
    {
        private readonly ObservableCollection<TestControlActualState> _testControlData;
        internal ReadOnlyObservableCollection<TestControlActualState> TestControlData { get; }

        public HMIModel()
        {
            _testControlData = new ObservableCollection<TestControlActualState>();
            TestControlData = new ReadOnlyObservableCollection<TestControlActualState>(_testControlData);
        }

...

        private void StartPollerThread()
        {
            _pollerCancellationToken ??= new CancellationTokenSource();

            if (!_pollerCancellationToken.IsCancellationRequested)
            {
                Task.Factory.StartNew(() => PollerDoWork(_pollerCancellationToken.Token), TaskCreationOptions.LongRunning);
            }
        }

        private void PollerDoWork(CancellationToken cancellationToken)
        {
            try
            {
                Thread.CurrentThread.Priority = ThreadPriority.Lowest;
                IsPollerStarted = true;

                while (!cancellationToken.IsCancellationRequested && (_isKeepConnection || _countOfTrying <= MAX_COUNT_OF_TRYING))
                {
                    try
                    {
                        _testControlData.Add(_emulator.GetTestControlActualState());

                        if (!_isKeepConnection && _countOfTrying > 0)
                        {
                            Thread.Sleep(_pollerTimeout / REASK_COEFICIENT);
                            continue;
                        }
                    }
                    catch
                    {
                        // Thread must be alive!!! ...ALWAYS!!!
                    }
                    Thread.Sleep(_pollerTimeout);
                }
            }
            finally
            {
                IsPollerStarted = false;
                _pollerCancellationToken = null;
            }
        }
0 votes
4k views

Getting an exception when trying to add tooltip template MVVM style to a blox plot. The chart also contains a scatter plot which should not be styled. That works fine, hoverwer, when I move the mouse over a box in the box plot, the exception is thrown.

I want to keep the styling, I just want to write something different than the default text.

The template:

  <DataTemplate DataType="scalarPlot:ToolTipData" x:Key="BoxSeriesTooltipTemplate">
    <TextBlock>
      <Run Text="Max:      " />
      <Run Text="{Binding Maximum}" />
      <LineBreak />
      <Run Text="P90:       " />
      <Run Text="{Binding P90}" />
      <LineBreak />
      <Run Text="Median: " />
      <Run Text="{Binding Median}" />
      <LineBreak />
      <Run Text="P10:       " />
      <Run Text="{Binding P10}" />
      <LineBreak />
      <Run Text="Min:       " />
      <Run Text="{Binding Minimum}" />
      <LineBreak />
    </TextBlock>
  </DataTemplate>

The binding:

      <Style TargetType="s:BaseRenderableSeries" x:Key="BoxSeriesStyle">
        <Setter Property="s:TooltipModifier.TooltipTemplate" Value="{StaticResource BoxSeriesTooltipTemplate}"/>
        <Setter Property="s:TooltipModifier.IncludeSeries" Value="True"/>
      </Style>

The modifier:

<s:SciChartSurface.ChartModifier>
      <s:ModifierGroup>
        <s:TooltipModifier IsEnabled="True" ShowTooltipOn="Always" ReceiveHandledEvents="True" TooltipLabelDataContextSelector="{Binding ToolTipDataContext}"/>
      </s:ModifierGroup>
    </s:SciChartSurface.ChartModifier>

The view model:

    private static IRenderableSeriesViewModel CreateBoxPlotViewModel(BoxPlotDataSeries<int, float> boxPlotDataSeries)
    {
        return new BoxPlotRenderableSeriesViewModel
        {
            DataSeries = boxPlotDataSeries,
            Stroke = Colors.SteelBlue,
            Fill = new LinearGradientBrush(Colors.White, Colors.LightSteelBlue, new System.Windows.Point(0, 0), new System.Windows.Point(0.5, 1)),
            StyleKey = "BoxSeriesStyle"
        };
    }

The data context selector:

    public Func<SeriesInfo, object> ToolTipDataContext
    {
        get
        {
            return seriesInfo =>
                   {
                       return seriesInfo switch
                       {
                           BoxPlotSeriesInfo boxInfo =>
                               new ToolTipData
                               {
                                   Fill = seriesInfo.Fill,
                                   Stroke = seriesInfo.Stroke,
                                   Maximum = (float) boxInfo.MaximumValue,
                                   P90 = (float) boxInfo.UpperQuartileValue,
                                   Median = (float) boxInfo.MedianValue,
                                   P10 = (float) boxInfo.LowerQuartileValue,
                                   Minimum = (float) boxInfo.MinimumValue
                               },
                           _ => seriesInfo
                       };
                   };
        }
    }
  • Tore Munch asked 3 years ago
  • last active 3 years ago
0 votes
8k views

Hi,

I have several chart panes that share a mouse group and a shared visual range (I inject the shared visual range of type IRange in the constructor of the pane view model). I then set the XAxis visual range to the shared visual range inside each pane view model. However, when I use either of the below approaches outside of the pane view model to adjust the min and max of shared visual range, the Xaxis.VisualRange of each pane does not reflect that change.

Approach A: _sharedVisualRange.Min = ….; _sharedVisualRange.Max = …
Approach B: _sharedVisualRange.SetMinMax(….)

Neither approach actually impacts the XAxis.VisualRange.Min/Max.

Initially when I created the XAxis in code I set its VisualRange equal to the shared visual range that was injected via constructor, like :

XAxis = new CategoryDateTimeAxis()
{
……
……
VisualRange = _sharedVisualRange,
…..
};

Please note that all the above refers to code in the view model. I bind the XAxis in the pane view model to the XAxis of the surface in xaml.

My entire synchronization heavily relies on the assumption of this working, but it does not.

  • bbmat asked 6 years ago
  • last active 6 years ago
0 votes
4k views

We’re using ReactiveUI and bindings in code-behind. We’re now upgrading from SciChart v3 to v6 and we’re wondering how to use the SeriesBinding in code-behind like this:

public partial class BarChartView : ReactiveUserControl<sBarChartViewModel>
{
    public BarChartView()
    {
        InitializeComponent();

        this.WhenActivated(disposable =>
        {
            this.OneWayBind(ViewModel,
                            vm => vm.SeriesSource,
                            view => view.BarChart.SeriesSource)
                .DisposeWith(disposable);

            this.OneWayBind(ViewModel,
                            vm => vm.LabelProvider,
                            view => view.FaciesAxis.LabelProvider)
                .DisposeWith(disposable);

            this.OneWayBind(ViewModel,
                            vm => vm.TooltipDataContext,
                            view => view.TooltipModifier.TooltipLabelDataContextSelector)
                .DisposeWith(disposable);

            this.OneWayBind(ViewModel,
                            vm => vm.XAxisRange,
                            view => view.FaciesAxis.VisibleRange)
                .DisposeWith(disposable);
        });
    }
}

Now the IChartSeriesViewModel and SciChartSurface.SeriesSource is deprecated so we have to move to IRenderableSeriesViewModel instead and then bind to SciChartSurface.RenderableSeries. But how can we convert from IRenderableSeriesViewModel to IRenderableSeries here?

  • Tore Munch asked 3 years ago
  • last active 2 years ago
Showing 51 - 79 of 79 results