Search code examples
c#arraysindexingpropertiesinotifypropertychanged

How do I get notified when an array property changes?


My class contain many properties and i need to handle each properties.

See this below:

public partial class my_form : Form
{
    private Image[] _imagelist;
    public Image[] imagelist
    {
        get
        {
            return _imagelist;
        }
        set
        {
            this._imagelist = value;
            this.on_imagelist_changed();
        }
    }

    private void on_imagelist_changed()
    {
        // do something.
    }

    private void button1_Click(object sender, EventArgs e)
    {
        /* set new imagelist */
        this.imagelist = getimagelist();
    }
}

Yes, It's work fine.

But when i call like this.

public partial class my_form
{
    private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        int selectedIndex = this.listView1.SelectedItems[0].ImageIndex;
        this.imagelist[selectedIndex] = dosomething(this.imagelist[selectedIndex]);
    }
}

It's don't call on_imagelist_changed(). Why ?

I can't add property by indexer like this. :(

public partial class my_form
{
    public Image imagelist[int x]
    {
        get
        {
            return _imagelist[x];
        }
        set
        {
            this._imagelist[x] = value;
            this.on_imagelist_changed();
        }            
    }
}

Can anyone help me solve this problem ?

Can i avoid to make a control class like this C# Indexers ?

I founded some suggestion, they told me let try ObservableCollection. I don't understand about this. May be someone example for me ?


Solution

  • It's don't call on_imagelist_changed(). Why?

    Because, quite bluntly, imageList has not changed. Some images inside imageList may have changed, but your code reacts only to the change of the entire imageList. The assignment calls get of your property twice; it never calls the setter.

    I can't add property by indexer like this.

    That's correct. However, you correctly noted that you could use an observable collection:

    public ObservableCollection<Image> Images {get;}
    
    private void OnImageListChanged(
        object sender
    ,   NotifyCollectionChangedEventArgs e) {
        // do something.
    }
    
    public MyForm() {
        Images = new ObservableCollection<Image>();
        Images.CollectionChanged += OnImageListChanged;
    }