Search code examples
c#wpflivecharts

While using wpf live chart library, I can't show line chart from data. I suspect data binding mistake


I'm Trying to show a cartesian chart using data from DB. But I'm stuck at showing data to chart.

I checked the data is correctly put into seriescollection. So I think there is an error at data binding.

This is my code at xaml file.

<wpf:CartesianChart Name="mainChart" Grid.Row="1" Grid.ColumnSpan="8" Height="250" Series="{Binding mainData}">
    <wpf:CartesianChart.AxisX>
        <wpf:Axis Title="Date" Labels="{Binding mainDataLabel}"></wpf:Axis>
    </wpf:CartesianChart.AxisX>
</wpf:CartesianChart>

And below is some part of my code related with the chart.

public partial class MainWindow : Window
{
    private SeriesCollection mainData;
    private List<string> mainDataLabel;

    public void GetDataAsCondition(SearchCondition condition)
    {

        // Here is some code to get data from DB

        for (int idx = 0; idx < mainDataTable.Columns.Count; idx++)
        {
            if (idx > 0)
            {
                LineSeries tmpLineSeries = new LineSeries();
                List<int> tmpDataList = new List<int>();
                tmpLineSeries.Title = mainDataTable.Columns[idx].ColumnName;

                for (int rowCnt = 0; rowCnt < mainDataTable.Rows.Count; rowCnt++)
                {
                    tmpDataList.Add(Int32.Parse(mainDataTable.Rows[rowCnt][idx].ToString()));
                }
                tmpLineSeries.Values = new ChartValues<int>(tmpDataList);

                mainData.Add(tmpLineSeries);

            }
            else if (idx == 0)
            {

                for (int rowCnt = 0; rowCnt < mainDataTable.Rows.Count; rowCnt++)
                {
                    mainDataLabel.Add(mainDataTable.Rows[rowCnt][idx].ToString());
                }

            }
        }
    }
}

I've checked binding property 'mainData' is declared at mainwindow class. So I think the binding should work. Where did I make a mistake in this code? Please help.

Thank you.


Solution

  • You're trying to perform the binding to a private field, which is wrong. If you want the binding to work properly mainData and mainDataLabel have to be public properties, instead of fields.

    So... It should be:

    
    public List<string> MainDataLabel { get;set; }
    
    public SeriesCollection MainData { get;set; }
    

    I hope it works for you :)