Another .NET Blog

To content | To menu | To search

Tag - View-Model

Entries feed - Comments feed

Wednesday 1 September 2010

[PostSharp] Fire INotifyPropertyChanged.OnPropertyChanged for read-only properties depending on other properties

One problem of the INotifyPropertyChanged aspect concerns automatic notification of read-only properties which depend on other properties.

Indeed, say you have this class, on which the aspect is applied:

[NotifyPropertyChanged]
public class Test
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string FullName { get { return FirstName + " " + LastName; } }
}

If you change the values of FirstName or LastName, the OnPropertyChanged event will be fired, and the view will be able to display the new values of the properties. But if a control of your view is bound to the FullName property, it won't be updated. A solution would be to declare FullName as an automatic property, and update it in the setters of FirstName and LastName. Not very practical.

In this article, I will show you how to extend the aspect, in order to make it fire the event for dependent properties when a "parent" property is modified.

Continue reading...

Monday 23 August 2010

[Ninject] Use one database session per view-model

One very useful web page I've read before beginning to code on my new project was this one: Data Access - Building a Desktop To-Do Application with NHibernate, from the well-known Ayende. In this article, among other hints and best-practices, he says, at the end of the Managing Sessions chapter:

The recommended practice for desktop applications is to use a session per form, so that each form in the application has its own session. Each form usually represents a distinct piece of work that the user would like to perform, so matching session lifetime to the form lifetime works quite well in practice. The added benefit is that you no longer have a problem with memory leaks, because when you close a form in the application, you also dispose of the session. This would make all the entities that were loaded by the session eligible for reclamation by the garbage collector (GC).

There are additional reasons for preferring a single session per form. You can take advantage of NHibernate’s change tracking, so it will flush all changes to the database when you commit the transaction. It also creates an isolation barrier between the different forms, so you can commit changes to a single entity without worrying about changes to other entities that are shown on other forms.

While this style of managing the session lifetime is described as a session per form, in practice you usually manage the session per presenter.

We'll see now how to implement this behavior, with Caliburn as the MVVM client framework, and Ninject as the dependency injector.

Continue reading...