Question

I was wondering if there was a way of calling a method or updating a property on my ViewModel object when WPF binds to the object ?

The reason I want to do this is that when my viewModel objects get created their data model only contains an ID that is used to query data from the database when necessary. So when the user navigates to that object I want the view to notify the ViewModel object that its being watched and as a result tell the data model to update its values from the DB and put my ViewModel object into a loading state

If the ViewModel objects knew to update them selves when they were displayed on screen I could avoid having to manually refresh all the objects.

Thanks!

Was it helpful?

Solution

When WPF binds to the object in your ViewModel, it's going to use the properties getter to fetch the value.

It sounds like you're trying to use lazy evaluation - just make the getter lazily instantiate the information from the DB:

private int entityId; // Set in advance
private Entity entityToFetch; // Will be fetched lazily

public Entity EntityToFetch
{
    get 
    {
        if (this.entityToFetch == null) // || this.entityToFetch.Id != this.entityId) - add this if you're letting this change at runtime...
        {
            this.entityToFetch = DataAccessLayer.FetchEntityForId(this.entityId);
        }

        return this.entityToFetch;
    }
}

OTHER TIPS

You could add a Selected property to your ViewModel that gets set when the object becomes selected. When Selected turns to true, you could hit up your database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top