Geysser Sdz
Geysser Sdz

Reputation: 85

WPF calculated ViewModel and property changed notification

I stumbled on this problem a few days ago and nothing seems to give me a solution - or, at least, an idea. In my ViewModel A I have a calculated property that produces an ObservableCollection of ViewModels B. I can bind to this collection no problem, but changes in the properties of ViewModel B items don't show up in the UI. Any ideas will be greatly appreciated and don't hesitate to ask for any clarification or detail. Thanks in advance!

Update: Here's the property that doesn't notify

public Boolean IsHighlighted
{
     get { return _IsHighlighted; }
     set
     {
          if (_IsHighlighted != value)
          {
               _IsHighlighted = value;
               OnPropertyChanged("IsHighlighted");
          }
      }
}

and the calculated property that produces the collection in ViewModel A

public ObservableCollection<PointViewModel> MidPoints
        {
            get
            {
                ObservableCollection<PointViewModel> midPoints = new ObservableCollection<PointViewModel>();
                // 
                //....calculations
                //
                return midPoints;
            }
        }

Upvotes: 0

Views: 176

Answers (1)

Clemens
Clemens

Reputation: 128156

Do not create a new ObservableCollection<PointViewModel> instance in the MidPoints property getter.

Instead, perform add and delete operations on the existing instance:

private readonly ObservableCollection<PointViewModel> midPoints
    = new ObservableCollection<PointViewModel>();

public ObservableCollection<PointViewModel> MidPoints
{
    get { return midPoints; }
}

public void UpdateMidPoints()
{
    // performs calculations that add and remove elements to/from midPoints
    // ...
}

In case it is for whatever reason required to create a new collection instance, you would have to raise the PropertyChanged event:

private ObservableCollection<PointViewModel> midPoints;

public ObservableCollection<PointViewModel> MidPoints
{
    get { return midPoints; }
    set
    {
         midPoints = value;
         OnPropertyChanged("MidPoints");
    }
}

public void UpdateMidPoints()
{
    ObservableCollection<PointViewModel> newMidPoints
        = new ObservableCollection<PointViewModel>();
    // 
    // calculations...
    //
    MidPoints = newMidPoints;
}

Upvotes: 1

Related Questions