Hello,
How to do bind data from DataTable to Chart series?
I get null reference exception.
I tried binding with square brackets and it did not worked either.
So, how to do the binding?
Thanks.
P.S:
I included DataGrid XAML and CS which works just fine.
Converting data to List<KeyValuePair<string,int>> works good but it is kinda slow and is unnessesary trash in code.
I use WPFToolkit (the latest version).
XAML:
<Window x:Class="BindingzTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="606" Width="988" xmlns:charting="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit">
<Grid Name="LayoutRoot">
<charting:Chart Title="Letters and Numbers" VerticalAlignment="Top" Height="400">
<charting:Chart.Series>
<charting:ColumnSeries Name="myChartSeries" IndependentValueBinding="{Binding Letter}" DependentValueBinding="{Binding Number}" ItemsSource="{Binding}" />
</charting:Chart.Series>
</charting:Chart>
<DataGrid Name="myDataGrid" VerticalAlignment="Stretch" Margin="0,400,0,50" ItemsSource="{Binding}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Letter" Binding="{Binding Letter}"/>
<DataGridTextColumn Header="Number" Binding="{Binding Number}"/>
</DataGrid.Columns>
</DataGrid>
<Button Content="Generate" HorizontalAlignment="Left" Name="generateButton" Width="128" Click="GenerateButtonClicked" Height="52" VerticalAlignment="Bottom" />
</Grid>
CS:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
DataTable GenerateMyTable()
{
var myTable = new DataTable("MyTable");
myTable.Columns.Add("Letter");
myTable.Columns.Add("Number");
myTable.Rows.Add("A", 500);
myTable.Rows.Add("B", 400);
myTable.Rows.Add("C", 500);
myTable.Rows.Add("D", 600);
myTable.Rows.Add("E", 300);
myTable.Rows.Add("F", 200);
return myTable;
}
private void GenerateButtonClicked(object sender, RoutedEventArgs e)
{
var myGeneratedTable = GenerateMyTable();
myDataGrid.DataContext = myGeneratedTable;
myChartSeries.DataContext = myGeneratedTable; // Calling this throws "Object reference not set to an instance of an object" exception
}
}