DataVisualization.Charting图表不适用于ObservableList

时间:2017-03-23 15:40:49

标签: c# wpf charts observable

我正在尝试将System.Windows.Controls.DataVisualization.Charting图表与某些ObservableCollection结合使用。

我为一个数据点创建了类:

public class ChartDataPoint : INotifyPropertyChanged
{
    private double xvalue;

    public double XValue
    {
        get { return xvalue; }
        set {
            if (xvalue != value)
            { 
                xvalue = value;
                NotifyPropertyChanged("XValue");
            }
        }
    }

    private double yvalue;

    public double YValue
    {
        get { return yvalue; }
        set {
            if (yvalue != value)
            {
                yvalue = value;
                NotifyPropertyChanged("YValue");
            }
        }
    }

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="x"></param>
    /// <param name="y"></param>
    private ChartDataPoint(double x, double y)
    {
        this.XValue = x;
        this.YValue = y;
    }

    public static ChartDataPoint CreateNew(double x, double y)
    {
        return new ChartDataPoint(x, y);
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}

然后我创建了ObservableCollection<ChartDataPoint>

public MainWindow()
{
    InitializeComponent();
    ListSeries1Data.CollectionChanged += ListSeries1Data_CollectionChanged;
    Chart1.DataContext = ListSeries1Data;
}

我的窗口出现后,我点击了一个按钮,将项目添加到我的列表中:

private void Button_Click(object sender, RoutedEventArgs e)
    {
        ListSeries1Data.Add(ChartDataPoint.CreateNew(i, r.Next(100)));
        i++;
    }

这是我的XAML的一部分,带有此图表。

 <c:Chart Name="Chart1" Background="WhiteSmoke">
        <c:LineSeries Name="Series1" 
                      Title="Read value"
                      IndependentValueBinding="{Binding Path=XValue}"
                      DependentValueBinding="{Binding Path=YValue}">
        </c:LineSeries>
</c:Chart>

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

您需要为系列添加ItemsSource。像这样:

<chartingToolkit:Chart Name="Chart1" Background="WhiteSmoke">
        <chartingToolkit:LineSeries Name="Series1" 
                  Title="Read value"
                  ItemsSource="{Binding}"
                  IndependentValueBinding="{Binding Path=XValue}"
                  DependentValueBinding="{Binding Path=YValue}">
        </chartingToolkit:LineSeries>
 </chartingToolkit:Chart>