This project is read-only.

Presenter as DependencyObject

Oct 24, 2007 at 5:35 AM

Does anyone foresee any side effects in doing something like this:

public abstract class Presenter<TView> : DependencyObject, IDisposable {}

and in the view(WPF):

public static readonly DependencyProperty PresenterProperty =
DependencyProperty.Register("Presenter", typeof (TestPresenter ), typeof (View));

public TestPresenter Presenter{
get { return (TestPresenter GetValue(PresenterProperty); }
set {
SetValue(PresenterProperty, value);
Presenter.View = this;

With that you can create dependency properties on the presenter and bind them directly into the view.

Oct 24, 2007 at 9:07 AM
Edited Oct 24, 2007 at 9:07 AM
Hi csanchez,

I can think of a few reasons not to do that:
  • your presenter is tied to the UI thread and its properties will only be accessible from the thread on which it was created
  • your unit tests will have to run from an STA thread (I think)
  • you're tying your presenters to a particular UI technology (WPF)

The last point is the big one. The main reason presenters exist is to separate out the logic into a class that is easily unit testable. Easily unit testable implies severing the tie to a particular UI platform (winforms, WPF, whatever). You're basically re-introducing that tie and will run into all the problems that the pattern is supposed to help you avoid.

Your goal is a worthy one though, I think. Note that the properties on the presenter don't have to be dependency properties in order for the view to bind to them. You can have your presenter implement INotifyPropertyChanged instead.

Oct 26, 2007 at 3:13 PM
Hi csanchez

I agree with Kent on these points. Also, the point is a a minor one, but most WPF documentation states that in your getters and setters for a Dependency prorperty, you should only have calls to GetValue and SetValue. Your example above violates this. When doing something like this, you should instead implment a propery changed event handler for your property and add any addition processing code there. One question I have is to why you want to do this anyway. This is suggesting that you expect your presenter to change, is somehow involved in DataBinding. Surely once the presenter has been created fora particular view, it should not change after that fact.

As Kent suggests, I have all my presenters implement INotifyPropertyChanged. This is very useful as you can also expose other properties on your presenter, and then your presenter can be used as the DataContext of the View. So your presenter can load some data, expose it as property, and making use of INotifyPropertyChanged, and then the View can bind to the properties of the Presenter.



Oct 27, 2007 at 12:30 AM

Thanks for your responses.

You're right, I overlooked INotifyPropertyChanged trying to acomplish a cleaner databinding with dependency properties.

I'm trying right now INotifyPropertyChanged and obtaining the same results without the intrusiveness.