Click to See Complete Forum and Search --> : Simple databinding scenario


yoyosh
April 14th, 2009, 06:21 AM
I`m trying to simulate simple two-way databinding mechanism. I have declared simple class for that purpose:

public class Car : INotifyPropertyChanged
{
string color;

public string Color
{
get { return color; }
set
{
color = value;
OnPropertyChanged("Color");
}
}



public event PropertyChangedEventHandler PropertyChanged;

void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(null, new PropertyChangedEventArgs(propertyName));
}
}

I have also created object of that class in Window1.cs file:

public partial class Window1 : Window
{
Car veh = new Car();


public Window1()
{
InitializeComponent();

veh.Color="red";

this.DataContext = veh;
}
...


I have binded this object`s color property for a textbox:


<TextBox Canvas.Left="276" Canvas.Top="66" Height="19.277" Width="101">
<TextBox.Text>
<Binding Path="Color" Mode="TwoWay"></Binding>
</TextBox.Text>
</TextBox>


Value in this textbox doesn`t refresh however when property of business object changes. What is wrong?

gstercken
April 20th, 2009, 06:50 AM
This happens because in your OnPropertyChanged() implementation, you are passing null as the source object. You should pass a reference to the changed object ('this', in this case) instead:

void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}