LiveCharts的基础知识 - 如何画线?

时间:2017-03-03 22:50:22

标签: c# .net wpf xaml livecharts

我很难理解LiveCharts实际应该发生的事情。我在这里有一块XAML:

<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>

代码在这里:

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

    myChart.Series.Add(mySeries);
}

在运行时,&#39; myChart.Series.Add(mySeries)&#39;抛出Null Reference Exception错误。我不确定如何解决这个问题?

1 个答案:

答案 0 :(得分:7)

因为您在不使用MVVM的情况下直接将系列添加到图表中,所以您不需要XAML中的所有绑定。你可以这样做:

<强> 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