使用WPF工具包绑定饼图不显示点

时间:2015-08-05 20:11:21

标签: c# wpf xaml mvvm charts

我有一个饼图,我已经定义如下:

        <chartingToolkit:Chart DataContext="1,10 2,20 3,30 4,40" 
                           HorizontalAlignment="Left" Margin="334,238,0,0" 
                           Name="chart1"  VerticalAlignment="Top" Height="177"
                           Width="218" BorderBrush="#00000000">
        <chartingToolkit:PieSeries 
        ItemsSource="{Binding PieCollection}"
        IndependentValueBinding="{Binding Path=Name}"
        DependentValueBinding="{Binding Path=Share}" />
    </chartingToolkit:Chart>

我的xaml也在这里引用:

 xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit">

那里没问题。我在ViewModel中声明了一个数据集:

 private ObservableCollection<PiePoint> _pieCollection;
 public ObservableCollection<PiePoint> PieCollection { get { return _pieCollection; } set { _pieCollection = value; OnPropertyChanged("PieCollection"); } }

PiePoint是我定义的对象,如下所示:

    public class PiePoint
    {
        public string Name { get; set; }
        public Int16 Share { get; set; }
    }

当我在构造函数中启动我的ViewModel时,我在这里添加了一些测试数据点,看看我是否可以在我的图表上获得一些数据:

    PieCollection = new ObservableCollection<PiePoint>();
    PieCollection.Add(new PiePoint { Name = "Mango", Share = 10 });
    PieCollection.Add(new PiePoint { Name = "Banana", Share = 36 });

但图表上没有任何内容。断点命中,我看到图表的背景,我知道项目源绑定到正确的集合,但我似乎无法让它工作。有什么建议吗?

1 个答案:

答案 0 :(得分:3)

这是我使用您的数据所得到的:

XAML:

SELECT
    p.productID, 
    p.productName,
    COUNT(t.productID) AS transCount
FROM
    product p
    INNER JOIN transaction t ON t.productID = p.productID
HAVING
    transCount > 10;  

结果:

enter image description here

请注意,我在XAML中创建了<Grid> <chartingToolkit:Chart Margin="0" Title="Chart Title"> <chartingToolkit:Chart.DataContext> <local:PieCollection/> </chartingToolkit:Chart.DataContext> <chartingToolkit:PieSeries ItemsSource="{Binding Mode=OneWay}" DependentValuePath="Share" IndependentValuePath="Name" DataContext="{Binding Mode=OneWay}" > </chartingToolkit:PieSeries> </chartingToolkit:Chart> </Grid> ,因此它与图表的PieCollection相关联。在您的情况下,您在代码中创建了DataContext,因此您可能需要执行类似

的操作
PieCollection

编辑:动态创建chart.DataContext = PieCollection

PieCollection

结果:

enter image description here