如何从ViewModel为ColumnSeries图表设置SelectedItem

时间:2011-07-21 13:45:04

标签: silverlight-4.0 mvvm charts

我有一个ColumnSeries图表,我想从视图模型中控制所选项目。我通过将图表的SelectedItem绑定到视图模型上的对象来完成此操作。

    <chartingToolkit:Chart Grid.Row="2" VerticalAlignment="Stretch"  HorizontalAlignment="Stretch" BorderThickness="0" MinHeight="200" Margin="0" x:Name="ratingsChart"  Style="{StaticResource ChartWithoutLegendStyle}">
        <chartingToolkit:Chart.Series>
            <chartingToolkit:ColumnSeries x:Name="chartRatingColSeries" IsSelectionEnabled="True"
                                          SelectedItem="{Binding SelectedRatingDistribution, Mode=TwoWay}"
                                          ItemsSource="{Binding RatingsList}" 
                                          IndependentValueBinding="{Binding RatingName}" 
                                          DependentValueBinding="{Binding NumberOfGoodies}">
            </chartingToolkit:ColumnSeries>
        </chartingToolkit:Chart.Series>
    </chartingToolkit:Chart>

页面上有各种元素会强制重新加载图表的数据(通过Web服务)。当我需要重新加载图表数据(从视图模型)时,我想将图表的SelectedItem设置为第一个数据点。这似乎工作除了图表没有直观显示(默认为红色)所选项目。以下是在Web服务调用后重新加载数据并重置所选项目的示例代码:

private RatingDistribution _selectedRatingDistribution = new RatingDistribution();
        public RatingDistribution SelectedRatingDistribution
        {
            get { return _selectedRatingDistribution; }
            set
            {
                _selectedRatingDistribution = value;
                RaisePropertyChanged("SelectedRatingDistribution");
            }
        }


        private ObservableCollection<RatingDistribution> _lstRatings = new ObservableCollection<RatingDistribution>();
        public ObservableCollection<RatingDistribution> RatingsList
        {
            get { return _lstRatings; }
            set
            {
                _lstRatings = value;
                RaisePropertyChanged("RatingsList");
            }
        }

        private void GetRatingsDistributionCompleted(object sender, GetRatingsDistributionCompletedEventArgs e)
        {
            IsBusy = false;

            RatingsList.Clear();
            foreach (RatingDistribution rd in e.Result)
                RatingsList.Add(rd);

            SelectedRatingDistribution = RatingsList[0];
        }

从View模型设置SelectedRatingDistribution不会在视觉上以红色直观显示图表上的选定项目。任何想法??

更新: 因此,如果我单击某列,图表会正确显示所选项目为红色,如下所示:correct behavior

但如果我从视图模型中设置SelectedItem,该列将不会显示为红色(作为所选项目)

1 个答案:

答案 0 :(得分:0)

以下更改功能修复了问题..

    private void GetRatingsDistributionCompleted(object sender, GetRatingsDistributionCompletedEventArgs e) {
        RatingsList.Clear(); 
        foreach (RatingDistribution rd in e.Result) 
            RatingsList.Add(rd);

        App.Current.RootVisual.Dispatcher.BeginInvoke(new Action(delegate() { SelectedRatingDistribution = RatingsList[0]; }));
    }