更新模型时,UI会相应更新,但是当我更新具有双向绑定的文本框时,不会调用视图模型中的setter。我做错了什么?
以下是视图模型绑定视图的方式
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}"/>
视图模型
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));
}
}
答案 0 :(得分:2)
<TextBox x:Name="TextBox1" Grid.Column="0" Text="{Binding SelectedEntity.Prop1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
TextBox的默认UpdateSourceTrigger是LostFocus我相信,所以你需要明确地将它设置为PropertyChanged。这样,只要属性发生变化,它就会触发。
答案 1 :(得分:0)
为了记录,即使双向绑定也不足够。似乎从绑定实例更新值时不会调用绑定程序实例的setter,即使您成功为旧值分配了新值也是如此。您需要在声明期间设置Dependency属性的PropertyChangedCallback回调以捕获此更改。