Reputation: 491
I am using the Chart in System.Windows.Controls.DataVisualization.Toolkit and binding to an object of type
ObservableCollection<KeyValuePair<double, double>>
I have my chart set up as in the picture below, and the screenshot has me hovering over the binding source so I know it is binding to the right object. But when I run the program the Chart is completely blank. I know this setup works, I use the exact same code in another program and it works perfectly. The only things I can think of is some missing references or somehow the style of the line not being set.
Edit:
Here is my code, it is a Runge-Kutta differential equation solver. I included the line you gave me near the bottom.
public MainWindow()
{
InitializeComponent();
}
ObservableCollection<KeyValuePair<double, double>> points = new ObservableCollection<KeyValuePair<double, double>>();
private double function(double t, double y)
{
return y + t;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
points.Clear();
points.Add(new KeyValuePair<double, double>(0, 1));
double h = .01;
for (int i = 0; i < 100; i++)
{
double k1 = function(points[i].Key, points[i].Value);
double k2 = function(points[i].Key + (h / 2.0), points[i].Value + (h / 2.0) * k1);
double k3 = function(points[i].Key + (h / 2.0), points[i].Value + (h / 2.0) * k2);
double k4 = function(points[i].Key + h, points[i].Value + h * k3);
double t = points[i].Key + h;
double y = points[i].Value + (h / 6.0) * (k1 + 2 * k2 + 2 * k3 + k4);
points.Add(new KeyValuePair<double, double>(t, y));
}
chart.DataContext = points;
}
Edit (solved):
I refactored into an MVVM project and it works perfectly now. So the moral is, stay away from code behind, even on tiny side projects.
Upvotes: 1
Views: 826
Reputation: 13188
Do this:
In your Window_Loaded
event:
chart.DataContext = points;
In your XAML:
<chartingToolkit:Chart x:Name="chart" Margin="0" Title="Chart Title">
<chartingToolkit:LineSeries DependentValuePath="Value" IndependentValuePath="Key" ItemsSource="{Binding}" />
</chartingToolkit:Chart>
EDIT: Full code:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Random r = new Random();
ObservableCollection<KeyValuePair<double, double>> points = new ObservableCollection<KeyValuePair<double, double>>();
for (int i = 0; i < 20; i++)
points.Add(new KeyValuePair<double, double>(i, r.NextDouble()));
chart1.DataContext = points;
}
}
This is the chart using your points:
Upvotes: 1