WPF在集合更改时重新计算

时间:2017-01-23 10:31:48

标签: c# wpf

基本上我有一组QuestionID, StudentName, Answer形式的答案。我想显示为当前问题提交的答案数量。好像我可以简单地通过集合已经改变事件的通知来做,但是我没有在视图上显示更新的计数。什么错误的想法?或者更好的方法呢?

已编辑为包含我的BaseViewModel

 public class BaseViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));
        }
}

public class AnswersViewModel : BaseViewModel{        
private static ObservableCollection<Answer> _answers;

    public AnswersViewModel()
    {           
        _answers = GetAnswers();

    }

    public static ObservableCollection<Answer> Answers { get {return _answers;} }

    public ObservableCollection<Answer> GetAnswers()
    {
        if (_answers == null)
        {
            _answers = new ObservableCollection<Answer>();
            _answers.CollectionChanged += new NotifyCollectionChangedEventHandler(Answers_CollectionChanged);
        }

        return _answers;
    }

    void Answers_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        System.Diagnostics.Debug.Print("Fired!!!!!!!"); /* Yes, it's fired*/
        OnPropertyChanged("NumAnswers");
    }

    public int NumAnswers
    {
        get
        {   
            /*THIS IS NOT BEING FIRED!*/
            int questionId = QuizViewModel.GetQuestionID();
            int numAns = (from ans in _answers where ans.QuestionID == questionId select ans).Count();
            System.Diagnostics.Debug.Print("numAns: " + numAns); 
            return numAns;
        }

    }
}

数据上下文中的ViewModel:

public class CompositeViewModel
{
    public AnswersViewModel answersVM { get; set; }
    //...other view models
    public CompositeViewModel()
    {
        this.answersVM = new AnswersViewModel();
      //... other view models
    }
}

XAML:

<DockPanel >
        <DockPanel.DataContext>
            <viewmodel:CompositeViewModel/>
        </DockPanel.DataContext>
        ....
        <TextBlock Text="{Binding Path=answersVM.NumAnswers, Mode=Default,UpdateSourceTrigger=PropertyChanged}"/>
        <TextBlock Text="{Binding Path=answersVM.Answers.Count, Mode=Default,UpdateSourceTrigger=PropertyChanged}"/> <!--This works as expected-->
</DockPanel>

0 个答案:

没有答案