我正在使用MVVM和SL4。我有一个绑定(bind)到ItemsControl的VoteResults集合。我想要每个Evo VoteResult项目中的PieChart。 VoteResult项目对象的属性如下所示:VotedYes 10;投票否4;弃权2; DidntVote 6;

如何通过这些VoteItem属性值在XAML中构建饼图的系列ItemSource?
就像是 :

 <charting:Chart>
    <charting:Chart.Series>
       <charting:PieSeries>
          <charting:PieSeries.ItemsSource>
             <controls:ObjectCollection>

             </controls:ObjectCollection>
          </charting:PieSeries.ItemsSource>
       </charting:PieSeries>
    </charting:Chart.Series>
 </charting:Chart>

最佳答案

图表控件旨在显示已处理并汇总好的数据以供呈现。

在我看来,您希望PieSeries展示一个包含类别“VotedYes”,“VotedNo”,“弃权”和“不投票”的系列,并将其作为独立值,而投票数作为从属值。在这种情况下,您需要将包含此数据集的集合传递给ItemsSource,单个对象则不会。

您将需要通过一个返回IEnumerable<KeyValuePair<String, Int32>>之类的函数来传递VoteResult对象。

 public IEnumerable<KeyValuePair<String, Int32>> ProcessVoteResult(VoteResult vr)
 {
      yield return new KeyValuePair<String, In232>("Voted Yes", vr.VotedYes);
      yield return new KeyValuePair<String, In232>("Voted No", vr.VotedNo);
      yield return new KeyValuePair<String, In232>("Abstained", vr.Abstained);
      yield return new KeyValuePair<String, In232>("Did Not Vote ", vr.DidntVote );
 }

现在,由于您似乎正在使用MVVM(通过查看其他问题),您可能需要绑定(bind)VoteResult。您将需要一个值转换器:-

 public class VoteResultToEnumerableConverter
 {
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
         if (value != null)
         {
              return ProcessVoteResult((VoteResult)value);
         }
         return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
         throw new NotImplementedException();
    }
 }

然后,您可以在图表上方的某个静态资源中使用此转换器:-
 <local:VoteResultToEnumerableConverter x:Key="vrconv" />

那么您的图表将如下所示:
 <toolkit:Chart>
     <toolkit:PieSeries
         ItemsSource="{Binding SomeVoteResult, Converter={StaticResource vrconv}}"
         DependentValuePath="Key"
         IndependendValuePath="Value"/>
 </toolkit:Chart>

关于silverlight - 饼图XAML绑定(bind),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6088619/

10-13 00:05