Reputation: 75
When the model is updated, the UI is updated accordingly, but when I update the textbox that has two-way binding, the setter in the view-model is not called. What am I doing wrong?
Here is how view-model is bound to view
public partial class MyView : MetroWindow
{
public MyView()
{
try
{
InitializeComponent();
DataContext = new MyViewModel(new DialogService(this));
}
catch (Exception exception)
{
throw exception;
}
}
}
xaml
<TextBox x:Name="TextBox1" Grid.Column="0" Text="{Binding SelectedEntity.Prop1, >Mode=TwoWay}"
controls:TextBoxHelper.ClearTextButton="True"
controls:TextBoxHelper.IsWaitingForData="True"
controls:TextBoxHelper.UseFloatingWatermark="True"
controls:TextBoxHelper.Watermark="{x:Static >properties:Resources.Prop1}" />
<TextBox x:Name="TextBox2" Grid.Column="0" Text="{Binding SelectedEntity.Prop2}"
controls:TextBoxHelper.ClearTextButton="True"
controls:TextBoxHelper.IsWaitingForData="True"
controls:TextBoxHelper.UseFloatingWatermark="True"
controls:TextBoxHelper.Watermark="{x:Static >properties:Resources.Prop2}"/>
The view-model
public class MyViewModel : IMyViewModel, INotifyPropertyChanged
{
private readonly IDialogService _dialogService;
public event PropertyChangedEventHandler PropertyChanged;
private readonly MyModel _model;
private MyEntity _selectedEntity;
public MyViewModel(IDialogService dialogService)
{
_dialogService = dialogService;
_selectedEntity = new MyEntity();
_model = new MyModel();
_model.PropertyChanged += _model_PropertyChanged;
}
public MyEntity SelectedEntity
{
get
{
var information = _model.GetInformation();
_selectedEntity.Flight = information.Prop1;
information.Destination = information.Prop2;
return _selectedEntity;
}
set
{
_selectedEntity = value;
OnPropertyChanged("SelectedEntity");
}
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Upvotes: 1
Views: 3233
Reputation: 8247
For the record, even twoway binding isn't sufficient. It seems, binder instance's setter isn't called when you update the value from binded instance, even if you succeed in assigning the old value with new value. You need to set PropertyChangedCallback callback of the Dependency Property during declaration to capture this change.
Upvotes: 1
Reputation: 180
<TextBox x:Name="TextBox1" Grid.Column="0" Text="{Binding SelectedEntity.Prop1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
The Default UpdateSourceTrigger for TextBox is LostFocus I believe, so you need to explicitly set it to PropertyChanged. This way it will fire whenever the property changes.
Upvotes: 4