Create an instance of SfChart totally in code-behind

I am trying to create a method in a Shared library which returns a PDFImage element on which I have drawn an SfChart control.  The method accepts two classes, one for the title and a description to display below the graph and the other is a set of datapoints for display.  I'm running into the "you MUST call Xamarin.Forms.Init() prior to using it" error when I try to set the title on the chart.  Any help would be helpful.


        public void GenReport()
        {
            ReportBlock blockInfo = new ReportBlock();
            blockInfo.Title = "Testing Results";
            blockInfo.Notes = "This test shows something but we're not sure what";

            ObservableCollection<ReportChart> dataPoints = new ObservableCollection<ReportChart>();
            dataPoints.Add(new ReportChart("First", 100));
            dataPoints.Add(new ReportChart("Second", 150));
            dataPoints.Add(new ReportChart("Third", 210));

            PdfImage newChart = GenerateChart(blockInfo, dataPoints);
        }
        public PdfImage GenerateChart(ReportBlock blockInfo, ObservableCollection<ReportChart> dataPoints)
        {
            string fileName = "outChart.jpg";
            PdfBitmap chartout;

            SfChart chart = new SfChart();
            chart.Title.Text = blockInfo.Title;
            chart.Title.TextAlignment = TextAlignment.Center;
           
            BarSeries bar = new BarSeries();
            bar.ItemsSource = dataPoints;
            bar.XBindingPath = "Name";
            bar.YBindingPath = "Value";
            chart.Series.Add(bar);
           
            chart.SaveAsImage(fileName);

            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                chartout = new PdfBitmap(fs);
            }

            File.Delete(fileName);
            return chartout;
        }


1 Reply

DV Divya Venkatesan Syncfusion Team January 31, 2018 12:16 PM UTC

Hi Christopher, 
 
We suspect the reported issue occurs since you have not set PrimaryAxis and SecondaryAxis for SfChart. Please set the PrimaryAxis and SecondaryAxis of SfChart as shown in the below code snippet. 
 
chart.PrimaryAxis = new CategoryAxis(); 
chart.SecondaryAxis = new NumericalAxis(); 
 
Please let us know, if you need further assistance. 
 
Regards, 
Divya Venkatesan 
 


Loader.
Up arrow icon