c# - LiveCharts 基础知识——如何画线?

标签 c# .net wpf xaml livecharts

我很难理解 LiveCharts 到底应该发生什么。我这里有一 block 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);
}

在运行时,“myChart.Series.Add(mySeries)”会引发 Null Reference Exception 错误。我不确定如何解决这个问题?

最佳答案

因为您是将系列直接添加到图表中,而不使用 MVVM,所以您不需要 XAML 中的所有绑定(bind)。你可以简单地这样做:

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

关于c# - LiveCharts 基础知识——如何画线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42589775/

相关文章:

c# - 如何修复开关运算符中的错误

wpf - 用 Gjallarhorn 显示对话窗口的好方法是什么?

c# - sql server 从表中选择百分比并从另一个表中选择所有数据

.net - 将 DataContext 对象作为 'ref' 参数传递有什么缺点吗?

c# - 如何通过Word文档修改 "walk"的内容?

c# - 保存整个ListView的图像

wpf - 使 Viewbox 垂直缩放但水平拉伸(stretch)

c# - 为什么表格单元格宽度不随 CSS 改变?

c# - 如何在 Avalonia 表单中强制键盘输入焦点

c# - 使用未知类型动态构建 LINQ 表达式