Linguistic forms

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

October 23, 2009 · Leave a Comment

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));
}
}
}

Categories: Uncategorized

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment