INotifyPropertyChanged vs. DependencyProperty in V

2018-12-31 10:15发布

When implementing the ViewModel in a Model-View-ViewModel architecture WPF application there seem to be two major choices how to make it databindable. I have seen implementations that use DependencyProperty for properties the View is going to bind against and I have seen the ViewModel implementing INotifyPropertyChanged instead.

My question is when should I prefer one over the other? Are there any performance differences? Is it really a good idea to give the ViewModel dependencies to WPF? What else do I need to consider when make the design decision?

14条回答
姐姐魅力值爆表
2楼-- · 2018-12-31 11:08

INotifyPropertyChanged when used also gives you the ability to add more logic in the code of your getters and setter of your properties.

DependencyProperty example:

public static DependencyProperty NameProperty = DependencyProperty.Register( "Name", typeof( String), typeof( Customer ) );

public String Name
{
    set { SetValue( NameProperty, value ); }
    get { return ( String ) GetValue( NameProperty ); }
}

In your getter and setter --- all you can do is simply call SetValue and GetValue respectively, b/c in other parts of the framework the getter/setter is not called, instead it directly calls SetValue, GetValue, so your property logic wouldnt reliably be executed.

With INotifyPropertyChanged, define an event:

public event PropertyChangedEventHandler PropertyChanged;

And then simply have any logic anywhere in your code, then call:

// ...
// Something cool...
// ...

if( this.PropertyChanged != null )
{
    PropertyChanged( this, new PropertyChangedEventArgs( "Name" ) );
}

// More cool stuff that will reliably happen...

This could be in a getter/setter, or anywhere else.

查看更多
长期被迫恋爱
3楼-- · 2018-12-31 11:09

From an expressiveness standpoint, I thoroughly enjoy using dependency properties and cringe at the thought of INotifyPropertyChanged. Apart from the string property names and possible memory leaks due to event subscription, INotifyPropertyChanged is a much more explicit mechanism.

Dependency properties imply "when this, do that" using easily-understood static metadata. It is a declarative approach that gets my vote for elegance.

查看更多
登录 后发表回答