Home > Software engineering >  How to get instances that get edited from observable collection? not added or removed
How to get instances that get edited from observable collection? not added or removed

Time:01-19

There is a observable collection in my class and I want to be notified when the observable collection changes.

I searched on stackoverflow and found this code

 private void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                foreach (var item in e.OldItems)
                {
                    //Removed items
                    
                }
            }
            else if (e.Action == NotifyCollectionChangedAction.Add)
            {
                foreach (var item in e.NewItems)
                {
                    //Added items
                }
            }
            else if(e.Action == NotifyCollectionChangedAction.Replace){
                foreach (var item in e.NewItems)
                {

                }
            }
        }

Every thing was working fine. I get notified when something created and deleted. but I didnt get notified when an instance edited. what did I do wrong?

Edit: I changed the observable collection to binding list but nothing is happeng when I edit something.

 <ListView Grid.Row="1" ItemsSource="{Binding Contacts}">
        <ListView.View>
        <GridView>
            <GridView.Columns>
                <GridViewColumn>
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                                <TextBox Text={Binding Name}></TextBox>
                                <TextBox Text={Binding Email}><TextBox>
                            </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView.Columns>
        </GridView>
        </ListView.View>
    </ListView>

And my viewModel:

    private BindingList<ContactViewModel> _contacts;
    public IEnumerable<ContactViewModel> Contacts=>_contacts;
    public ContactListing()
    {
        _contacts.ListChanged  =_contacts_ListChanged;          

    }

    private void _contacts_ListChanged(object sender, ListChangedEventArgs e)
    {
        //Get Notified When somthing is edited
    }

in the xaml I have some texboxes that when the text of them changes, The binding list or observable collection also changes(I set a breakpoint and the list was changing everytime something edited) but the ListChanged event doesnot call.

CodePudding user response:

The collection element must implement INotifyPropertyChanged. And the collection needs to be replaced with enter image description here

BaseInpc class from here: https://stackoverflow.com/a/67617794/13349759 .

  • Related