将数据绑定到UWP WinRT_XamlToolKit_Chart

时间:2017-04-05 19:48:51

标签: c# uwp winrt-xaml-toolkit

我正在尝试使用WinRT_XamlToolkit_Chart库从UWP程序中的DataTemplate加载图表。我使用{Binding Property}语法绑定图表标题和数据,但它没有将该属性作为图表对象的数据成员加载。我已经包含了我的XAML

<Charting:Chart HorizontalAlignment="Center" 
                VerticalAlignment="Center" 
                Width="600" 
                Height="400" 
                DataContext="{Binding}"
                Title="{Binding Title}">
    <Charting:LineSeries Title="{Binding Title}" 
                         Margin="0" 
                         IndependentValuePath="Name" 
                         DependentValuePath="Amount" 
                         IsSelectionEnabled="True" 
                         ItemsSource="{Binding Data}"
                         />
</Charting:Chart>

c#Object

public class DataChartNode : ExperimentNode
{
    public DataChartNode(String title, String type)
    {
        Type = type;
        Title = title;
        Category = "Data Analysis";
    }

    public DataChartNode(String type)
    {
        Type = type;
        Category = "Data Analysis";
        Name = type;
        Title = "Hello";
        Length = 0;
        Data = new List<DataPoint>();
    }

    public DataChartNode() { }

    public string Type { set; get; }
    public string Title { set; get; }
    public int Length { set; get; }
    public List<DataPoint> Data { set; get; }
}

1 个答案:

答案 0 :(得分:0)

由于您没有提供DataPoint类,并且没有显示如何构建绑定到Chart控件的数据源,因此我编写了一个简单的演示后面的数据源代码可以与您可以参考的XAML代码段一起使用。

XAML代码(与您相同)

<Charting:Chart
    Title="{Binding Title}"
    Width="600"
    Height="400"
    HorizontalAlignment="Center"
    VerticalAlignment="Center"
    DataContext="{Binding}">
    <Charting:LineSeries
        Title="Title"
        Margin="0"
        DependentValuePath="Amount"
        IndependentValuePath="Name"
        IsSelectionEnabled="True"
        ItemsSource="{Binding Data}" />
</Charting:Chart>

背后的代码

public sealed partial class MainPage : Page
{
    private Random _random = new Random();
    public MainPage()
    {
        this.InitializeComponent();
        var data = new List<DataPoint>();         
        for (int i = 0; i < 3; i++)
        {
            data.Add(new DataPoint { Name = "Name" + i, Amount = _random.Next(10, 100) });              
        }
        DataChartNode charnode = new DataChartNode()
        {
            Title = "Hello",
            Data = data
        };          
        this.DataContext = charnode;     
    }
}
public class DataChartNode
{
    public string Type { set; get; }
    public string Title { set; get; }
    public int Length { set; get; }
    public List<DataPoint> Data { set; get; }
}
public class DataPoint
{
    public string Name { get; set; }
    public int Amount { get; set; }      
}

请检查后面的代码,找出是否有任何问题。