Search code examples
powershelleventsobservablecollection

PowerShell Observable Collection Event


I am trying to register the PropertyChanged event for an Observable Collection in PowerShell, but no dice. This works just fine for the CollectionChanged event.

This works:

Register-ObjectEvent -InputObject $MyObservableCollection -EventName CollectionChanged -Action {Write-Host "Collection changed!"}`

Whereas this does not work:

Register-ObjectEvent -InputObject $MyObservableCollection -EventName PropertyChanged -Action {Write-Host "Property changed!"}`

The error I receive is as follows:

Register-ObjectEvent : Cannot register for the specified event. An event with the name 'PropertyChanged' does not exist.


Solution

  • Looks like you need to create a class that support the Property changed, so you could do something like this:

    $PersonClass = @'
    using System.ComponentModel;
    
    public class Person : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
        private string _Name;
        public string Name
        {
            get { return _Name; }
            set
            {
                _Name = value;
    
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Name"));
            }
        }
    
        private string _Age;
        public string Age
        {
            get { return _Age; }
            set
            {
                _Age = value;
    
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Age"));
            }
        }
    
        private string _Country;
        public string Country
        {
            get { return _Country; }
            set
            {
                _Country = value;
    
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Country"));
            }
        }
    }
    '@
    Add-Type -TypeDefinition $PersonClass -Language 'CSharp'
    $NewPerson = [Person]::New()
    $MyObservableCollection = New-Object -TypeName System.Collections.ObjectModel.ObservableCollection[Person]
    
    Register-ObjectEvent -InputObject $NewPerson -EventName PropertyChanged -Action {Write-Host  "PropertyChanged on item"}
    Register-ObjectEvent -InputObject $MyObservableCollection -EventName CollectionChanged -Action {Write-Host "Item added or removed"}
    
    $MyObservableCollection.Add($NewPerson)
    $NewPerson.Name = 'Joe Bloggs'
    

    Here we are creating a Person class which stores the properties of a person like Name, Age and country, each with a PopertyChangedEventHandler. Once you have that its then creating an observable arraylist so you can add/remove individual Persons from the list (which will trigger the CollectionChanged event).