Should I leave out INotifyPropertyChanged? - wpf

when I have a ViewModel, could there be cases where I can leave out INotifyPropertyChanged? I seem to get that this interface is used when you have multiple displays of a property in a GUI, so that when this property is edited, all the displays of the adjusted property get the new value. But what if you are fairly certain that UI will only have one display of the property?

I use NotifyPropertyWeaver - it generates property notification code for you. Then there is no reason why not to implement it in types that might potentially need it.

I'd always implement INotifyPropertyChanged because requirements might change.
The binding mode supports OneWay and OneTime so overhead can be reduced.
Inheriting from a base class will make it easy to implement the interface so I see no real advantages of not implementing INotifyPropertyChanged on a ViewModel.

It is OK to leave out INotifyPropertyChanged in two cases:
The property is not databound
The value of the property is never changed after the data binding is set up.
This is unlickly to be the case for a WPF ViewModel.

Related

Advantage of Binding?

I am not sure that I fully understand the advantage of binding. For example, if I want to bind a string value to a TextBlock I need to do the following:
Create a class that extends INotifyPropertyChanged
Add a string to that class (say: MyString)
Extend the set method for MyString so that it calls another method (say: OnPropertyChanged)
Create the OnPropertyChanged method to call the PropertyChangedEventHandler event
Then I need to create a new instance of the class, set my TextBlock.DataContext to point to that class, and finally add the XAML bit for the binding.
Can someone explain the advantage of this over simply setting:
TextBlock.Text = MyString;
Thanks!
Any changes to MyString won't be automatically reflected in your UI.
Your code behind will be littered with "when this event occurs, update these pieces of data", so you'll essentially be writing your own messy data binding logic for each and every view.
The advantage is that you can both change and display the value in multiple places, without having to update some method to add another TextBlock assignment each time the value changes. Any new display control just binds itself to the property, the rest is automatic.
Now if you really just set the value in one place and show it in one control, then you're right, there's not much point.
The gain of using Data Binding isn't particularly noticeable for a TextBlock binding to a static string.
However if the value of MyString changes during application runtime it becomes much more useful - especially in a case where the object that owns that property is unaware of the TextBlock. This separation between UI and the underlying data layer can be created using a design pattern such as MVVM.
Data Binding is also useful for more complex properties such as Items in a ListBox control. Just bind the ListBox.Items to a property that is of type ObservableCollection and the UI will automatically update whenever the content of that collection changes.

Why do ViewModels need to implement INotifyPropertyChanged or use Dependency Properties?

I've seen many Tutorials about the MVVM-Patern but I still don't get why I need to get a Dependency-Property or an INotiyfyPropertyChanged-Property if I want to send information from the ViewModel back to the View.
Dependency properties provide built in change notification for when a property changes which means WPF knows when a controls value has changed.
Your ViewModel types do not, by default, provide any mechanism for change notification so if they don't support either of these options how is the view supposed to know when a property in your viewModel has been changed?
You need your viewModel to use either of these options so that the view can be notified when a property value changes.
This means if a property value is changed in code, the user interface is updated and if a property is changed by user input your viewModel (and ultimately your model) is also updated to reflect these changes. (basically both sides of a binding require a way of communicating a property change to each other).
The INotifyPropertyChanged interface is the preferred method as it means your viewModels are not specific to WPF and can be used by other user interface technologies. also, dependency properties can only be used in types that derive from DependencyObject.
First: You do not need to use INotifyPropertyChanged or DependencyObject at all.
But, and this is the central point in using Binding, there is some Pub / Sub Mechanism in
the Binding, which is listening to those PropertyChanged events and doing the update
of the view in case a relevant property for Binding has changed.
Here is more information on that:
SO on how binding works
Pub Sub aka Publish Subscribe Pattern
INotiyfyPropertyChanged - This property we used in the viewmodel so that if there happens any changes in the UI this property will reflect those changes.

INotifyPropertyChanged Question in Silverlight

i am working on MVVM and i am not much familiar with it and i would like to know where to implement INotifyPropertyChanged?
I implemented it in ViewModel (Which is correct from my understanding) and i am in a situation where i need to modify the retrieved data in the View and once the data is modified save it in a property and once the propriety in the View is assigned/changed i want the ComboBox pick up that itemsource which will be the property thats changed and holds the modified Data.
So what do i do in this situation? should i implement INotifyPropertyChanged in the View and use:
PropertyChanged += new PropertyChangedEventHandler(PropertyChanged_implimentation); ?
What do i do?
Typically you would implement INotifyPropertyChanged on your view models. You may also choose to implement it on your models, if you need to notify any consumer of their property changes (for example view models).
You wouldn't typically implement INotifyPropertyChanged on your view, as you would use XAML binding to communicate between your view and underlying view model.
INPC is required to notify your view to update itself whenever a property value changes in your view model. The binding engine will update the bound property values in your view model whenever a control value in your view changes.
A good introduction to MVVM can be found here, and I would also strongly recommend using an MVVM framework for any kind of serious app.

what is the difference between TwoWay databinding and ObservableCollection?

As i was reading about ObservableCollection i came to know that it implements INotifyPropertyChanged which means whenever the view changes it's underlying collection also gets updated automatically which is exactly what is the purpose of TwoWay databinding. So, what is the difference between ObservableCollection and TwoWay databinding?
Thanks in advance :)
The two "things" TwoWay databinding and ObservableCollection are different things which can collaborate, but are not directly linked. Databinding is a concept and ObservableCollection is an implementation of an interface (INotifyCollectionChanged) which is used in the implementation of the concept of databinding in the .NET framework. In itself, INotifyCollectionChanged is a small part of this implementation.
In fact you can use TwoWay databinding without ObservableCollections and ObservableCollections without databinding.
Databinding is a mecanism allowing you to bind a business object property (Often a ViewModel property) to an UI property. OneWay Databinding provides support for update of UI when the object is changed (which requires implementation of INotifyPropertyChanged and/or INotifyCollectionChanged on the business object). TwoWay Databinding provides twoway support as its name suggest it: Object => UI (like OneWay do) AND UI => Object. UI to Object updates does not requires implementation of INotifyCollectionChanged nor INotifyPropertyChanged.
Observable collection now is interesting because it implements INotifyCollectionChanged, which makes it a good candidate to create databindable collections. But I use often INotifyCollectionChanged without databinding, and I am pretty sure you can find other collections which implement INotifyCollectionChanged (like PagedCollectionView)
Does it answer your question?
If you bind to your collection like this {Binding Path=MyCollection, Mode=TwoWay} then reference to collection will be updated but not its contents. Observable collection allows to track its contents changes, but not reference change (MyCollection.Clear() will trigger UI update, but MyCollection = anotherInstance will not).
The question is a little bit like "what's the difference between a horse and a cart?"
An ObservableCollection can be used for TwoWay databinding (to an ItemsControl).
It is more or less designed to make databinding easy.
Whenever a Control updates an ObservableCollection or the other way around, there is a DataBinding in the middle.
Object needs to implement INotifyPropertyChanged so you are able to bind to properties of this object.
TwoWayDatabinding tells databinding engine it needs to update properties both ways.
You are comparing apples and airplanes. Those are two completly different things.
Also ObservableCollection also implements INotifyCollectionChanged that allows to notify its items changed, not only properties.

INotifyPropertyChanged vs. DependencyProperty in ViewModel

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?
Kent wrote an interesting blog about this topic: View Models: POCOs versus DependencyObjects.
Short summary:
DependencyObjects are not marked as
serializable
The DependencyObject class overrides and seals the Equals() and
GetHashCode() methods
A DependencyObject has thread affinity – it can only be accessed
on the thread on which it was
created
I prefer the POCO approach. A base class for PresentationModel (aka ViewModel) which implements INotifyPropertyChanged interface can be found here: http://compositeextensions.codeplex.com
According to the WPF performance guide, DependencyObjects definitely perform better than POCOs that implement INotifyPropertyChanged:
http://msdn.microsoft.com/en-us/library/bb613546.aspx
The choice is totally based on your business logic and UI abstraction level. If you dont want a good separation then DP will work for you.
DependencyProperties will be applicable mainly at the VisualElements level so it won't be good idea if we create lot of DPs for each of our business requirements. Also there is a greater cost for DP than a INotifyPropertyChanged. When you design a WPF/Silverlight try to design UI and ViewModel totally separate so that at any point of time we can change the Layout and UI controls (Based on theme and Styles)
Refer this post also - https://stackoverflow.com/questions/275098/what-applications-could-i-study-to-understand-datamodel-view-viewmodel . The link has a lot of reference to Model-View-ViewModel pattern, which is very relevant to this discussion.
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.
Dependency properties are intended to supports binding (as a target) on UI elements not as a source to data binding, this is where INotifyProperty comes in. From a pure point of view you shouldn't use DP on a ViewModels.
"In order to be the source of a binding, a property does not need to be a dependency property; you can use any CLR property as a binding source. However, in order to be the target of a binding, the property must be a dependency property. For a one-way or two-way binding to be effective, the source property must support change notifications that propagate to the binding system and thus the target. For custom CLR binding sources, this means that the property must support INotifyPropertyChanged. Collections should support INotifyCollectionChanged."
All dependency objects cannot be serialised (This could hamper the use of ViewModels and DTO (POCO)'s.
There are differences between DP within Silverlight compared to WPF.
http://msdn.microsoft.com/en-us/library/cc221408(v=VS.95).aspx
http://msdn.microsoft.com/en-us/library/cc903933(VS.95).aspx
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.
Is it really a good idea to give the ViewModel dependencies to WPF?
.NET 4.0 will have System.Xaml.dll, so you won't have to take a dependency on an arbitrary framework to utilize it. See Rob Relyea's post about his PDC session.
My take
XAML is a language for describing objects, and WPF is a framework whose described objects are UI elements.
Their relationship is similar to C#, a language for describing logic, and .NET, a framework which implements particular kinds of logic.
XAML's purpose is declarative object graphs. The W*F technologies are great candidates for this paradigm, but XAML exists independently of them.
XAML and the entire dependency system were implemented as separate stacks for WF and WPF, probably to leverage the experience of different teams without creating a dependency (no pun intended) between them.
I too had to consider this decision recently.
I found that the INotifyPropertyChanged mechanism suited my needs better because it allowed me to glue my GUI to an existing business logic framework without duplicating state. The framework I was using had its own observer pattern and it was easy to forward one level of notification on to the next. I simply had a class which implemented the observer interface from my business logic framework and the INotifyPropertyChanged interface.
With DP you cannot define the backend that stores the state yourself. I would have had to let .net cache a copy of every item of state I was binding to. This seemed like an unnecessary overhead - my state is large and complicated.
So here I found INotifyPropertyChanged better for exposing properties from business logic to GUI.
That being said where I needed a custom GUI widget to expose a property and for changes to that property to affect other GUI widgets DP proved the simple solution.
So there I found DP useful for GUI to GUI notification.
Dependency properties are the glue of custom control creation. If you are interested in using Intelli-sense to show your properties in the properties window at XAML design time you must use Dependency properties. INPC will never show a property in the property window at design time.
It seems that Dependency Properties should be used in controls that you create such as Buttons. To use properties in XAML and use all the WPF features, those properties must Dependency Properties.
However, your ViewModel is better off using INotifyPropertyChanged. Using INotifyPropertyChanged will give you the ability to have getter/setter logic if you need to.
I recommend checking out Josh Smith's version of a base class for a ViewModel that already implements INotifyPropertyChanged:
http://joshsmithonwpf.wordpress.com/2007/08/29/a-base-class-which-implements-inotifypropertychanged/
I think this is an excellent example of how to do a ViewModel.
I think DependencyProperty and INotifyPropertyChanged are used for two different things in Binding : the first for enabling a property to be a target of a binding and receive the input from another property (use {Binding ...} to set the property), the last when you want the value of a property to be used as the source of a binding (name in the Binding Path Expression).
So the choice is merely technical.
I prefer a more direct approach, which I blogged about in Presentation Model Without INotifyPropertyChanged. Using an alternative to data binding, you can bind directly to CLR properties without any bookkeeping code. You just write plain-old .NET code in your View Model, and it gets updated when your Data Model changes.
There is only one thing why to prefer a DependencyObject - Binding will work better. Just try an example with a ListBox and TextBox, populate list with data from INotifyPropertyChanged property vs. DependencyProperty and edit current item from TextBox...
If you want to expose properties to other controls you must use Dependency properties... But good luck because they take a while to figure out...

Resources