I have a TextBlock, binded with an Object and when i update property of object its not refleting on UI, Why ?
Code:
<TextBlock Name="txtName" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" Width="100" Height="20" Margin="12,23,166,218" />
public partial class Window1 : Window
{
Employee obj ;
public Window1()
{
InitializeComponent();
obj = new Employee();
obj.Name = "First";
txtName.DataContext = obj;
}
private void btnUpdate_Click(object sender, RoutedEventArgs e)
{
obj.Name = "changed";
}
}
public class Employee : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _name;
public string Name
{
set
{
this._name = value;
OnPropertyChanged(Name);
}
get { return this._name; }
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
OnPropertyChanged(Name);
should be:
OnPropertyChanged("Name");
otherwise if the name is set to "Kent", you're raising a property changed event saying that the "Kent" property has changed, which obviously doesn't exist.
As for UpdateSourceTrigger
, that only applies to the source. The property you've bound is the target, not the source. And it doesn't make sense for a TextBlock
to update its source, because there's no way for the user to modify the TextBlock
text. A TextBox
, on the other hand, would make sense. In that case, UpdateSourceTrigger
determines the point at which the text in the TextBox
is pushed back to the source property (e.g. as the user types each character, or when they move away from the TextBox
).
Pass the name of the property as string, instead of the property value, like so:
OnPropertyChanged("Name");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With