Mike Diaz
Mike Diaz

Reputation: 2065

Having ObservableCollection Trigger an update

So i have something along the lines of

private  ObservableCollection<ViewModel> _internal;

public ObservableCollection<ViewModel> BoundInternal{get;set}; //this is Binded in the Itemssource like ItemSource={Binding BoundInternal}

Now In my code i do something like

BoundInternal=_internal, However the problem is the BoundInternal isn't trigger any collectionChanged event. I have to use the Add method. So I am wondering if there is a solution to this.

Upvotes: 3

Views: 4430

Answers (2)

AnthonyWJones
AnthonyWJones

Reputation: 189457

Here is what I suspect your code ought to look like like (although its not quite a match for what you currently doing):-

public class YourClassHoldingThisStuff : INotifyProperyChanged
{
  private  ObservableCollection<ViewModel> _internal;

  public ObservableCollection<ViewModel> BoundInternal
  {
    get { return _internal; }
    set
    {
      _internal = value;
      NotifyPropertyChanged("BoundInternal");
    };
  }
  public event PropertyChangedEventHandler PropertyChanged;

  private void NotifyPropertyChanged(string name)
  {
    if (PropertyChanged != null)
      PropertyChanged(this, new ProperytChangedEventArgs(name));
  }
}

In this case the _internal field becomes the source of the value of BoundInternal directly and you should only assign it via BoundInternal, (don't assign a value directly to _internal). When that occurs anything currently bound to it will be informed of the change.

If for some reason you really do need to maintain _internal as a separate reference from the backing field of BoundInternal then:-

public class YourClassHoldingThisStuff : INotifyProperyChanged
{
  private  ObservableCollection<ViewModel> _internal;
  private  ObservableCollection<ViewModel> _boundInternal;

  public ObservableCollection<ViewModel> BoundInternal
  {
    get { return _boundInternal; }
    set
    {
      _boundInternal = value;
      NotifyPropertyChanged("BoundInternal");
    };
  }
  public event PropertyChangedEventHandler PropertyChanged;

  private void NotifyPropertyChanged(string name)
  {
    if (PropertyChanged != null)
      PropertyChanged(this, new ProperytChangedEventArgs(name));
  }
}

Now at some point in your code when you do BoundInternal = _internal, anything bound to it will be informed of the change.

Upvotes: 4

Mark
Mark

Reputation: 14930

Every ItemsControl has a, Items property which has a Refresh() method that you can call, which will update your list.

MyList.Items.Refresh()

Upvotes: 3

Related Questions