Search code examples
c#wpfentity-frameworkmvvmchange-tracking

How to notify UI when Entity set ChangeTracker has changes


I've created a WPF MVVM application that does some CRUD operation to an Entity set.

In the UI I have a save/commit button, what I'd like it do is create an event or notification in my ViewModel to the View when Entity set ChangeTracker has any changes and bind this to IsEnabled on the button.

How could I achieve this?

I know there is the following property that I could tap into:

dbcontext.ChangeTracker.HasChanges();

or

db.ChangeTracker.Entries().Any(e => e.State == EntityState.Added
                                 || e.State == EntityState.Modified
                                 || e.State == EntityState.Deleted);

I'm just not sure how to implement it


Solution

  • I would implement the following property on the ViewModel:

    public bool dbHasChanges => dbcontext.ChangeTracker.HasChanges();
    

    And then bind to it in the XAML:

    <Button IsEnabled="{Binding dbHasChanges}" />
    

    It would then be a case of raising a property changed notification on that property whenever the database is updated:

    NotifyPropertyChanged("dbHasChanges");
    

    This is for if the database is only changed from within your application (you would execute the above code whenever the user makes a change).

    You could also refactor this into a method so you're not hardcoding the property name more than once:

    private void DBChangeOccured()
    {
        NotifyPropertyChanged("dbHasChanges");
    }
    

    You could then just call this method instead of NotifyPropertyChanged.

    Update

    Rather than having a separate method to prevent hardcoding your property names, in .NET Core you can use:

    NotifyPropertyChanged(nameof(dbHasChanges));