Simple databinding scenario
I`m trying to simulate simple two-way databinding mechanism. I have declared simple class for that purpose:
Code:
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:
Code:
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:
Code:
<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?
Re: Simple databinding scenario
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:
Code:
void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}