Awarious OfficePortal - HRMS Application

wpf textbox databinding not updating viewmodel property

0 votes
asked Jul 4, 2013 in WPF by anonymous

I have written a very simple window with 2 textboxes. Both the textboxes are bound with the view model property. I have implemented INotifyPropertyChanged and raised the property changed event. Whenever the property value changed in the viewmodel, respective textbox value changed. But, when the textbox text property value changed, view model property is not getting changed. What am I missing in this code?

<StackPanel Grid.Row="1" Grid.Column="1" Orientation="Vertical">
 <TextBlock Text="{Binding Employee.FirstName}”  HorizontalAlignment="Left" MinWidth="130" VerticalAlignment="Center" Margin="0,5,0,5" />
 <TextBlock Text="{Binding Employee.LastName }" HorizontalAlignment="Left" MinWidth="130" VerticalAlignment="Center" Margin="0,5,0,5" />

1 Answer

+1 vote
answered Jul 4, 2013 by Aadhira (1,215 points)
selected Jul 4, 2013 by administrator
Best answer

In WPF databinding, INotifyPropertyChanged is used to inform the WPF controls about the the changes happened in the viewmodel properties. Because Text property of the TextBox control is a dependency object. So, by default, dependency object will be listening to the PropertyChanged event from the bound viewmodel property. That’s why changes from reflected to textbox.
But you have not done any code that informs view model property about the changes happened in the textbox. You can use UpdateSourceTrigger that is available in “Binding” class which is used in markup extension. This UpdateSourceTrigger accept different values. But below 2 are majorly used

“LostFocus” – Once you set this, textbox value gets changed, will be updated to view model property, whenever the textbox has lost focus.

“PropertyChanged” – This option will update the view model right after you type any single character.

<StackPanel Grid.Row="1" Orientation="Vertical">
 <TextBlock Text="{Binding Employee.FirstName, UpdateSourceTrigger=LostFocus}" HorizontalAlignment="Left" MinWidth="130" VerticalAlignment="Center" Margin="0,5,0,5" />
 <TextBlock Text="{Binding Employee.LastName, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" MinWidth="130" VerticalAlignment="Center" Margin="0,5,0,5" />

Your answer


Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
site design / logo / content © 2013 - 2019