Silverlight tip #1: Binding to an object property doesn’t work

If you select a binding to bind for example textbox text, you could use the binding in this way:

Text=”{Binding Source={StaticResource myViewModel}, Path=MyObject.SomeProperty, Mode=OneWay}”

You would expect this to bind to MyObject on the view model, and specificly to the SomeProperty property on MyObject. I expected this to work out of the box given that the view model would implemt INotifyPropertyChanged.

However – not only your view model needs to implement the INotifyPropertyChanged, but your MyObject class has to do this as well. For instance:

public class MyViewModel : INotifyPropertyChanged
private MyObject m_MyObject;
public MyObject
set { this.m_MyObject = value }
get { return this.m_MyObject; OnNotifyPropertyChanged(“MyObject”); }

public class MyObject : INotifyPropertyChanged
private String m_Id;

public String Id
get { return m_Id; }
set { m_Id = value; OnPropertyChanged(“Id”); }

By the way – I usually implement the INotifyPropertyChanged in a separate abstract class letting each view model inherit from this. For instance:

public abstract class ViewModel : INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged(string propertyName)
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler.Invoke(this, new PropertyChangedEventArgs(propertyName));


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s