Basics of LiveCharts -- How do I draw a Line?
Asked Answered
C

1

8

I'm having a very difficult time understanding what's actually supposed to be happening with LiveCharts. I have a block of XAML here:

<Grid>
    <Grid.Background>
        <ImageBrush ImageSource="/CPF;component/Images/background-top-cropped2.png" Stretch="None"></ImageBrush>
    </Grid.Background>
    <lvc:CartesianChart Series="{Binding myData}" LegendLocation="Right" x:Name="myChart">
        <lvc:CartesianChart.AxisY>
            <lvc:Axis Title="Sales" LabelFormatter="{Binding YFormatter}"></lvc:Axis>
        </lvc:CartesianChart.AxisY>
        <lvc:CartesianChart.AxisX>
            <lvc:Axis Title="Month" Labels="{Binding Labels}"></lvc:Axis>
        </lvc:CartesianChart.AxisX>
    </lvc:CartesianChart>
</Grid>

And code Behind here:

public MainWindow()
{
    InitializeComponent();
    DrawGraphs();
}
public void DrawGraphs()
{
    LineSeries mySeries = new LineSeries
    {
        Values = new ChartValues<int> { 12, 23, 55, 1 }
    };

    myChart.Series.Add(mySeries);
}

At runtime, 'myChart.Series.Add(mySeries)' throws a Null Reference Exception error. I'm unsure of how to resolve this?

Casper answered 3/3, 2017 at 22:50 Comment(0)
C
9

Because you're adding the series directly to the chart, without using MVVM, then you don't need all the binding in XAML. You can simply do this:

XAML:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
    xmlns:local="clr-namespace:WpfApplication1"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <lvc:CartesianChart x:Name="myChart" />
</Grid>

CS:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DrawGraphs();
    }
    public void DrawGraphs()
    {
        LineSeries mySeries = new LineSeries
        {
            Values = new ChartValues<int> { 12, 23, 55, 1 }
        };

        myChart.Series.Add(mySeries);
    }
}

enter image description here

Controller answered 4/3, 2017 at 1:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.