IsDirty using INotifyPropertyChanged on EF object

Given the form of editing std record using WPF two way binding to EF object object

The IsDirty handler is handled as follows

entity.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(ct_PropertyChanged);
DataContext = entity;

void entity_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    IsDirty = true;
}

void SaveAndClose()
{
    if ( IsDirty ) { // doSave }
    Close();
}

      

Everything works fine, except when the user changes only field X and deletes save (which is a valid model in this case!)

The problem is that PropertyChanged () is NOT called before closing (), so the entry is NOT saved

Any way to force "Binder" or any other alternatives?

+3


source to share


2 answers


I suppose that UpdateSourceTrigger

LostFocus

's why the property is updated when the control (filedX) loses focus. For example. the user clicks the cursor over another control.

One possibility is to install UpdateSourceTrigger

on PropertyChanged

.

Another way is to force the currently focused element to update the source code.



Here's an example for a TextBox:

var focusedElement = Keyboard.FocusedElement;
if(focusedElement is TextBox)
{
    var bindingExpression = ((TextBox)focusedElement).GetBindingExpression(TextBox.TextProperty);
    if(bindingExpression != null)
    {
        bindingExpression.UpdateSource();
    }
}

      

+1


source


By default, the Binding UpdateSourceTrigger is LostFocus, which means your binding will update the lining value when your control loses its Focus. You can change this property in PropertyChanged so that it updates the source as soon as the user clicks on it (or enters it if it is a TextBox).



+1


source







All Articles