2017-03-03 70 views
6

我很難理解實際上應該發生在LiveCharts上的事情。我有XAML這裏塊:這裏的背後LiveCharts基礎知識 - 如何繪製線條?

<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); 
} 

在運行時, 'myChart.Series.Add(mySeries)' 拋出一個空引用異常錯誤。我不確定如何解決這個問題?

回答

6

由於您直接將圖表添加到圖表,而不使用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