Detecting dirty using winforms data binding

2019-02-27 19:24发布

问题:

I am using 2 way binding with winforms text boxes. I need to work out if the user has changed my data Looking at the help for

the CurrentItemChanged Event

It seems that this event does fire if a property has changed, however it also fires if current has changed.

Is there a way to tell whether the data has changed?

a similar question is also asked here but not answered in my opinion

Oliver mentions "if your object within the List support the INotifyPropertyChanged event and you replace the List by a BindingList you can subscribe to the ListChanged event of the BindingList to get informed about any changes made by the user."

My application meets these conditions but I cant get this working. The ListChangedType.ItemChanged property looked hopeful, but it changes when I navigate to the next record without changing the data

I found a link at Microsoft here but surely it cant be that hard!

回答1:

This seems to work

void bindingSource_BindingComplete(object sender, BindingCompleteEventArgs e)
        {
            if (e.BindingCompleteContext == BindingCompleteContext.DataSourceUpdate)
            {
                var person = (Person)bindingSource.Current;

                if ( person.State == State.Unchanged && (e.BindingCompleteState == BindingCompleteState.Success)
                && e.Binding.Control.Focused)
                {
                    person.State = State.Modified;  // using Julie Lerman's repositories technique
                }
            }
        }